JavaScript equivalent of PHP's preg_replace

95,898

Solution 1

Use the global flag, g:

foo.replace(/<br>/g,"\n")

Solution 2

JS idiom for non-Regexp global replace:

input_content.split('<br>').join('\n')
Share:
95,898
ryonlife
Author by

ryonlife

Updated on September 27, 2020

Comments

  • ryonlife
    ryonlife over 3 years

    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.

  • JRsz
    JRsz almost 7 years
    I feel dirty using this but it works and is the only way if the regex expression is base 64 decoded. TY :)
  • Tamim
    Tamim about 6 years
    Hi @bobince, Asker wanted a RegEx based solution, why do you answer this?
  • Amit Patil
    Amit Patil about 6 years
    @Tamim The regex solution had already been given; this is an alternative as for simple string replacement regex isn't necessary.