Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know alot of answers are out there for string replace in javascript, but I can't find one for / to /. please help me out on this or send me some link to how to write regular expressions in so to replace. Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
969 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because a backslash is used as an escape character, you'll need to escape it:

str = str.replace("\/", "/");

The above replaces / with /. In general, anywhere you use a backslash in a string, you probably need to escape it. So, to replace / with /, you'd use:

str = str.replace("/", "/");

These will, of course, only replace one instance in the string. To replace multiple instances, use a regular expression with the g (global) modifier:

str = str.replace(/\/|/\/g, "/")

Here, because forward slashes have meaning as regex terminators, you're having to escape the forward slash as well as the backslash. The alternative is to use the RegExp class:

str = str.replace(new RegExp("\\/|/", "g"), "/")

In this one, you're having to escape the backslash twice — once to escape it in the string, and once in the regex. (Here's a better explanation.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...