I want to replace string in a paragraph where string may be combination of alphanumeric and slashes.
What i did:
var arrayFind = new Array('s\\if','t\\/');
var arrayReplace = new Array('If','q');
var arrayFindLength = arrayFind.length;
function replaceRightChar(str, parFind, parReplace){
for (var i = 0; i < arrayFindLength; i++) {
regex = new RegExp(parFind[i], "g");
str = str.replace(regex, parReplace[i]);
}
alert(str);
}
var mainData="s\\if t\\/ h\\ s\\";
replaceRightChar(mainData, arrayFind, arrayReplace);
Error:
Uncaught SyntaxError: Invalid regular expression: /s/: \ at end of pattern
My tests do not end up with any error. You did have a problem with double escaping, though.
Array('s\\if','t\\/');
should be (if I got right what you want)
Array('s\\\\if','t\\\\/');
Working example: jsfiddle
Edit: I still think that the problem is the double escaping. I updated my fiddle to test all the possible combinations.
Essentially I doubled the arrayFind
var arrayFind1 = new Array('s\\if','t\\/');
var arrayFind2 = new Array('s\\\\if','t\\\\/');
and the mainData
var mainData1="s\if t\/ h\\ s\\";
var mainData2="s\\if t\\/ h\\ s\\";
and quadruplicated the call
replaceRightChar(mainData1, arrayFind1, arrayReplace);
replaceRightChar(mainData1, arrayFind2, arrayReplace);
replaceRightChar(mainData2, arrayFind1, arrayReplace);
replaceRightChar(mainData2, arrayFind2, arrayReplace);
I guess the first or the fourth call are what you need
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With