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.

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?

4 Answers 4

50
var text = 'test   test   test test';
var fixed = text.replace(/\s+/g, '-');
Sign up to request clarification or add additional context in comments.

3 Comments

don't you need to put quote marks around the regular expression? or am I getting confused?
No, it's a regex literal. If we enclose it in quotes, JS will treat it like a regular string, which results in an empty match, since we don't have anything like /\s+/g in our text variable. More information can be found at MDN
Thanks for the reference :) turns out I was getting confused
6

javascripts string.replace function also takes a regular expression:

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

http://jsfiddle.net/5yn4s/

Comments

2

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

2 Comments

In this case it doesn't matter if it is ( )* or ( *) because you don't need the content of the capturing group, so you don't need the brackets at all: result = subject.replace(/ */g, "-"); will do exactly the same.
I think you should use + instead of *: you want to match one or more spaces, not zero or more. I haven't tested this, but otherwise it might produce -t-e-s-t-t-e-s-t-t-e-s-t-t-e-s-t-
0

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 :)

2 Comments

Needs a /g for global replacement
And needs to be replaced with '-', not ''.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.