Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript find and replace a set of characters?

Tags:

javascript

I have a string and I need to replace all the ' and etc to their proper value

I am using

var replace = str.replace(new RegExp("[']", "g"), "'");

To do so, but the problem is it seems to be replacing ' for each character (so for example, ' becomes '''''

Any help?

like image 522
Steven Avatar asked Dec 02 '22 01:12

Steven


1 Answers

Use this:

var str = str.replace(/'/g, "'");

['] is a character class. It means any of the characters inside of the braces.

This is why your /[']/ regex replaces every single char of ' by the replacement string.


If you want to use new RegExp instead of a regex literal:

var str = str.replace(new RegExp(''', 'g'), "'");

This has no benefit, except if you want to generate regexps at runtime.

like image 75
Arnaud Le Blanc Avatar answered Dec 19 '22 02:12

Arnaud Le Blanc