相当于 PHP preg_replace 的 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7079294/
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
JavaScript equivalent for PHP preg_replace
提问by Skyfe
I've been looking for a js-equivalent for the PHP preg_replace
function and what I found so far is simply string.replace
.
我一直在寻找 PHPpreg_replace
函数的 js 等效项,到目前为止我发现的只是string.replace
.
However I'm not sure how to convert my regular expression to JavaScript. This is my PHP code:
但是我不确定如何将我的正则表达式转换为 JavaScript。这是我的 PHP 代码:
preg_replace("/( )*/", $str, $str);
So for example the following:
因此,例如以下内容:
test test test test
becomes:
变成:
test-test-test-test
Anyone knows how I can do this in JavaScript?
任何人都知道我如何在 JavaScript 中做到这一点?
回答by ant_Ti
var text = 'test test test test',
fixed;
fixed = text.replace(/\s+/g, '-');
回答by Paul Creasey
javascripts string.replace function also takes a regular expression:
javascripts string.replace 函数也需要一个正则表达式:
"test test test test".replace(/ +/,'-');
回答by J0HN
回答by Arseni Mourzenko
In JavaScript, you would write it as:
在 JavaScript 中,您可以将其编写为:
result = subject.replace(/ +/g, "-");
By the way, are you sure you've posted the right PHP code? It would rather be:
顺便说一句,您确定您已经发布了正确的 PHP 代码吗?而是:
$result = preg_replace('/ +/', '-', $str);