Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace string in a string using value from array

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

like image 732
ßikrant Giri Avatar asked Jun 02 '26 11:06

ßikrant Giri


1 Answers

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

like image 143
dirluca Avatar answered Jun 04 '26 00:06

dirluca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!