0

I've got a function that will display urls visited by users e.g. https://stackoverflow.com/questions/78/of/103/uk/ask

I want to use a regex expression with javascript to capture a specific parameter of the url and replace it with placeholder text. Taking the example above;

When https://stackoverflow.com/questions/7845w98439/uk/ask is matched, replace the '/78/of/103/uk/' part with '/task/of/total/country/'. The code below I have doesn't seem to work. Can someone show me where I'm going wrong?

JS:

const url_change = [
 {expression: '/^/78/of/103/uk//i', value: '/task/of/total/country/'}
];
const urlParam = url_change.reduce(function(result, item) {
 return element.classList.contains(item.expression) ? item.value : result;
 }, '');
return urlParam(
 toChange ? toChange.value : getElementText(element)
);
asked Oct 12, 2018 at 10:55
1
  • you have to escape all slashes in the regexp /^\/bla\/bleh etc Commented Oct 12, 2018 at 10:59

1 Answer 1

2

Do as follow:

var str = "https://stackoverflow.com/questions/78/of/103/uk/ask";
const url_change = [
 {expression: /\/78\/of\/103\/uk\//i, value: '/task/of/total/country/'}
];
// console.log(url_change[0].expression.test(str));
var result = str.replace(url_change[0].expression,url_change[0].value);
console.log(result);

Sign / is special character (announces the end of Regex expression), it needs a mark \ lead to become a / in url, for Regex expression!

answered Oct 12, 2018 at 11:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.