Skip to content Skip to sidebar Skip to footer

Javascript Find And Replace Works With String But Not Variable

Hoping someone can help me it's driving me nuts. I am using SPServices and Javascript to rewrite some links after a small content migration. I have some HTML in a variable and I'm

Solution 1:

It does not work because some the characters in the string have a special meaning in a regular expression, like \ and .. So they need to be escaped.

You can use this function:

functionescapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}


var newHTML = '<a href="http://someplaintext/pages/GuidelinesaspxiPageId=14495"> my link </a>';
var oldLink = 'http://someplaintext/pages/GuidelinesaspxiPageId=14495';
var newLink = 'http://urlstart?id=14495';
newHTML = newHTML.replace(newRegExp(escapeRegExp(oldLink), 'gi'), newLink); 
console.log(newHTML);

See also this question.

Post a Comment for "Javascript Find And Replace Works With String But Not Variable"