JavaScript equivalent of PHP's preg_replace


Question

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.

1
71
9/27/2012 8:54:02 AM

Accepted Answer

Use the global flag, g:

foo.replace(/<br>/g,"\n")
125
8/29/2012 12:17:45 AM

JS idiom for non-Regexp global replace:

input_content.split('<br>').join('\n')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon