Get Data Key value and include in URL before .html

Viewed 109

Used below code to get value from data-key and join with .html.

Initial Url will be - http://www.test.com/en/location/london.html

Based on key value (Ex:258888) collected need to append inside url like http://www.test.com/en/location/london.258888.html

But, now it gets latest URL and including new key if user choose next option value. On each choose value, it includes to URL.

Like - http://www.test.com/en/location/london.258888.3899091.html

But, it have to be only.

http://www.test.com/en/location/london.3899091.html

$('a.dropdown-item').on('click', function(){
 let getDataKey = $(this).attr('data-key');
 let getWindowLocation = window.location.href;
 let getLocationVal = getWindowLocation.replace(/\.html/, '.' + getDataKey + '.html');
 window.location.replace(getLocationVal); 
});

1 Answers

You could also include the optional digit matcher [.0-9] in the regex.

[0-9] characters range 0-9
* zero or more of the preceding character .

Code Example:

$('a.dropdown-item').on('click', function(){
    let getDataKey = $(this).attr('data-key');
    let getWindowLocation = window.location.href;
    let getLocationVal = getWindowLocation.replace(/[.0-9]*\.html/, '.' + getDataKey + '.html');
    window.location.replace(getLocationVal); 
});

Demo:

let string1 = "http://www.test.com/en/location/london.html";
let string2 = "http://www.test.com/en/location/london.3899091.html";
console.log("String1 : " + string1.replace(/[.0-9]*\.html/, '.' + "454545.html"));
console.log("String2 : " + string2.replace(/[.0-9]*\.html/, '.' + "258888.html"));

Related