0

Hi i have this simple code:

 preg_replace('/[\r\n]+/', '</br>',$string);

i would like to replicate the same codein JS so i do:

string.replace('/[\r\n]+/','</br>');

but this won't work.

Also i would like to make it recursive using g , is it possible?

Thanks

2 Answers 2

4

replace() accepts a first parameter of type RegExp and you are passing a string, you need to change to:

string.replace(/[\r\n]+/,'</br>');

Also, replace() isn't a static method, in other words you don't call it like this. Instead you call it on the string on which you want to perform the replacement.

If you want to use g then you can:

string.replace(/[\r\n]+/g,'</br>');
                        ^
Sign up to request clarification or add additional context in comments.

7 Comments

I assume he was calling it on a variable called string.
@RocketHazmat Maybe, that is left to the OP to answer.
@sbaaaang: No quotes around the regex ;-)
@sbaaaang: That's Swiffer :-P
@Sniffer i removed my comment i called you Duster like the Swiffer but damn i confused Swiffer with Sniffer , sorry :D was just a joke :D you're welcome! and thnk you a lot ;)
|
2

In JavaScript, .replace supports both strings and regexes as what to replace. You sent it a string, it doesn't know it's a regex. It was looking for the literal string '/[\r\n]+/'.

You need to use a regex literal:

string.replace(/[\r\n]+/g,'</br>');

Yes, you can use use regexes like that, with no quotes!

You can use the new RegExp constructor if you want to use a string as your regex:

string.replace(new RegExp('/[\r\n]+/', 'g'),'</br>');

2 Comments

sorry i just accepted the most voted one, since i think both answers were awesome! thank you man!
@sbaaaang: Pick whichever one helped you the most :-)

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.