简体   繁体   中英

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.

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,"");

You also need to escape the *

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM