开发者

JavaScript equivalent for PHP preg_replace

开发者 https://www.devze.com 2023-03-28 05:36 出处:网络
I\'ve been looking for a js-equivalent for the PHP preg_replace function and what I found so far is simply string.replace.

I've been looking for a js-equivalent for the PHP preg_replace function and what I found so far is simply string.replace.

However I'm not sure how to convert my regular expre开发者_运维技巧ssion to JavaScript. This is my PHP code:

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?


var text = 'test   test   test test';
var fixed = text.replace(/\s+/g, '-');


javascripts string.replace function also takes a regular expression:

"test    test  test    test".replace(/ +/,'-');

http://jsfiddle.net/5yn4s/


In JavaScript, you would write it as:

result = subject.replace(/ +/g, "-");

By the way, are you sure you've posted the right PHP code? It would rather be:

$result = preg_replace('/ +/', '-', $str);


See javascript replace function reference.

In your case it is something like

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消