相当于 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:45:55  来源:igfitidea点击:

JavaScript equivalent for PHP preg_replace

phpjavascriptregexpreg-replace

提问by Skyfe

I've been looking for a js-equivalent for the PHP preg_replacefunction 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(/ +/,'-');

http://jsfiddle.net/5yn4s/

http://jsfiddle.net/5yn4s/

回答by J0HN

See javascript replacefunction reference.

请参阅 javascript替换函数参考。

In your case it is something like

在您的情况下,它类似于

var result = str.replace(/\s+/g, '-');

But that replaces only one space. Working on it now :)

但这仅替换了一个空格。现在正在努力:)

回答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);