Reputation: 365
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 expression 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?
Upvotes: 35
Views: 75357
Reputation: 2425
var text = 'test test test test';
var fixed = text.replace(/\s+/g, '-');
Upvotes: 49
Reputation: 52311
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);
Upvotes: 2
Reputation: 28824
javascripts string.replace function also takes a regular expression:
"test test test test".replace(/ +/,'-');
Upvotes: 6