javascript 替换问号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8718111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:20:21  来源:igfitidea点击:

javascript replace question mark

javascriptregex

提问by fish man

how to make a regex for ?and =in javascript?

如何为?=在 javascript 中制作正则表达式?

I want something from

我想要一些东西

http://localhost/search?search=words

http://localhost/search?search=words

to

http://localhost/search/search/words

http://localhost/search/search/words

(?search=) to (/search/)

(?search=) 到 (/search/)

<script>
var ss = "http://localhost/search?search=words".replace("/\?search\=/g", "/search/");
document.write(ss);
</script>

BTW: just some prastic, not a htaccss rewrite. Thanks.

顺便说一句:只是一些实用的,而不是 htaccss 重写。谢谢。

回答by Ansel Santosa

Almost there! =is not a special character and does not need to be escaped. In addition, regex strings are not wrapped by quotes. So:

快好了!=不是特殊字符,不需要转义。此外,正则表达式字符串没有被引号包裹。所以:

"http://localhost/search?search=words".replace(/\?search=/g, "/search/");

回答by Madara's Ghost

How about

怎么样

str.replace(/[?=]/g, "/");

Do note that it's probably better to make a function to understandthe url structure and rebuild it properly, that will produce a much more healthy, robust code, rather then a simple replacement.

请注意,最好创建一个函数来理解url 结构并正确重建它,这将产生更健康、更健壮的代码,而不是简单的替换。

回答by deviousdodo

You can use a simple string for replace:

您可以使用简单的字符串进行替换:

var ss = "http://localhost/search?search=words".replace("?search=", "/search/");