简体   繁体   中英

How do I use the JavaScript string replace method to replace the '+' sign?

All you need to know is in the question. I have a search query in the URL that looks like this:

http://www.mysite.com?param=word1+word2+word3

So far, I can retrieve "word1+word2+word3" but I can't seem to use something like:

document.write(str.replace(/+/g," "));

I want the final output to look like this: "word1 word2 word3"

Thanks for looking.

Try to escape the + sign using the escape char \\ since is a restricted char:

document.write(str.replace(/\+/g," "));

http://www.regular-expressions.info/javascript.html

The + is a special character in regex, if you want to match it literally you have to escape it. So try:

document.write(str.replace(/\+/g," "));

您必须转义+号,在正则表达式中它具有特殊含义。

document.write(str.replace(/\+/g," "));

尝试使用十六进制值

document.write(str.replace(/[\u002B]/g," "));

如何使用split()函数,在这种情况下似乎更简单:

document.write(str.split(",", " ");

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