JavaScript equivalent of PHP's preg_replace
Asked Answered
A

2

73

I am using a simple regex to replace break tags with newlines:

br_regex = /<br>/;
input_content = input_content.replace(br_regex, "\n");

This only replaces the first instance of a break tag, but I need to replace all. preg_match_all() would do the trick in PHP, but I'd like to know the JavaScript equivalent.

Agha answered 2/1, 2009 at 16:6 Comment(2)
As you don't need to match a regex pattern, you should be using str_replace() in PHP instead of preg_match_all() for your example: $str = str_replace('<br>', "\n", $str);Insensible
You should really change title saying preg_replace and not preg_match_all, this is confusing and doesn't help when searchingAutumnautumnal
M
135

Use the global flag, g:

foo.replace(/<br>/g,"\n")
Mead answered 2/1, 2009 at 16:8 Comment(0)
F
18

JS idiom for non-Regexp global replace:

input_content.split('<br>').join('\n')
Fausta answered 2/1, 2009 at 23:37 Comment(3)
I feel dirty using this but it works and is the only way if the regex expression is base 64 decoded. TY :)Threedecker
Hi @bobince, Asker wanted a RegEx based solution, why do you answer this?Entrance
@Entrance The regex solution had already been given; this is an alternative as for simple string replacement regex isn't necessary.Fausta

© 2022 - 2024 — McMap. All rights reserved.