4

This might be easy for those who play with regular expressions.

str = "Here is 'sample' test";
str = str .replace(new RegExp('"', 'g'), '');
str = str .replace(new RegExp("'", 'g'), '');

How to combine 2nd and 3rd line, I want to combine regular expressions new RegExp('"', 'g') and new RegExp("'", 'g') into one regular expression, this will make it in one line. Thanks in advance.

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
Riz
  • 9,165
  • 8
  • 36
  • 53

6 Answers6

8
str = str.replace(/"|'/g, '')
Andrew
  • 8,030
  • 11
  • 44
  • 74
3
str.replace(/['"]+/g, '')
SilentGhost
  • 287,765
  • 61
  • 300
  • 288
2

Try:

str = str.replace(new RegExp('["\']', 'g'), '');
Bart Kiers
  • 161,100
  • 35
  • 287
  • 281
0

You can simply use a character class for this, to match both single and double quotes you can use ['"].

In a full regex you would need to escape one of the quotes though.

var str = "here is 'sample' test";
str = str.replace(/["']/g, '');
Wolph
  • 74,301
  • 10
  • 131
  • 146
0

Similar to Andrew's solution:

str.replace(/"|'/, 'g')

And if you seeking for a good explanation then this has been discussed on a different threat where Alan Moore explains good. Read here.

Community
  • 1
  • 1
Ramiz Uddin
  • 4,271
  • 4
  • 37
  • 72
-1
str = "Here is 'sample' test".replace(new RegExp('"', 'g'), '').replace(new RegExp("'", 'g'), '');

An example that's basically the same as yours, except it uses method chaining.

darioo
  • 45,106
  • 10
  • 73
  • 103