Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a global replace on backslash in a string in javascript

I've tried: (Incase all the slashes make it hard to read, 1st line should replace forward slashes, 2nd line should replace backslashes, 3rd line should replace asterisks.

newbigbend = bb_val.replace(/\//gi,"");
newbigbend = bb_val.replace(/\\/gi,"");
newbigbend = bb_val.replace(/*/gi,"");

to replace all forward slashes, backslashes and asterisks. But when the browser gets to the middle line newbigbend = bb_val.replace(/\\/gi,""); it thinks its an unterminated comment. I know to use the escape to replace the forward slash. Not sure about back.

like image 481
Mike Felder Avatar asked Feb 25 '23 08:02

Mike Felder


1 Answers

Andrew Cooper's answer is correct in terms of why that third statement is going wrong. But you're also overwriting newbigbend each time, so you won't see the result of the first two replacements at all.

If you're trying to replace all slashes, backslashes, and asterisks with nothing, do this:

newbigbend = bb_val.replace(/[/\\*]/g, "");

Note you don't need the i flag, none of those characters is case sensitive anyway. (And note that within the [], you don't need to escape / or *, because they don't have special meaning there.) Live example.

But if you want it as three individual statements for whatever reason, then use newbigbend in the second two (and add the backslash Andrew flagged up):

newbigbend = bb_val.replace(/\//gi,"");
newbigbend = newbigbend.replace(/\\/gi,"");
newbigbend = newbigbend.replace(/\*/gi,"");
like image 86
T.J. Crowder Avatar answered Feb 26 '23 20:02

T.J. Crowder