JavaScript equivalent for PHP preg_replace

I was looking for the js equivalent for the PHP function preg_replace , and what I have found so far is just string.replace .

However, I'm not sure how to convert my regex 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 

Does anyone know how I can do this in JavaScript?

+8
javascript php regex preg-replace
source share
4 answers
 var text = 'test test test test', fixed; fixed = text.replace(/\s+/g, '-'); 
+16
source share

The javascripts string.replace function also accepts a regular expression:

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

http://jsfiddle.net/5yn4s/

+3
source share

See javacript replace function description.

In your case, this is something like

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

But this replaces only one space. Now we are working on it :)

0
source share

In JavaScript, you should write it as:

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

By the way, are you sure you posted the correct PHP code? That would be better:

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

All Articles