1

I have a string

$$_### ABC ###_$$ $$_### PQR ###_$$ $$_### XYZ ###_$$

I wanted to replace $$_### with and li tag and ###_$$ with a closing li tag.

So the final output should be <li>ABC</li><li>PQR</li><li>XYZ</li>

What I have used is this

str = $$_### ABC ###_$$ $$_### PQR ###_$$ $$_### XYZ ###_$$;

new_str = (str.replace(/$$_###/g,'<li>')).replace(/###_$$/g,'</li>');

It doesn't seem to be working.

new_str = (str.replace('$$_###','<li>').replace('###_$$','</li>'); worked fine, but of course i want a global replacement.

Any help will be deeply appreciated.

karthik manchala
  • 13,492
  • 1
  • 31
  • 55
Piyush
  • 63
  • 8

2 Answers2

4

$ is a special character in regex which asserts that we are at the end of a line. So you need to escape the dollar symbol in-order to match a literal $ symbol.

new_str = str.replace(/\$\$_###/g,'<li>').replace(/###_\$\$/g,'</li>');
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

$ is a special character in regex meaning end of line. You need to escape each one with a '\' in your regex literal per regular_expressions.

The replace is just doing a literal replace of text so it requires no escaping.

Here is a link where you can see it working and test it - regex101

cchamberlain
  • 17,444
  • 7
  • 59
  • 72