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
  • 307,395
  • 66
  • 306
  • 293
Riz
  • 9,703
  • 8
  • 38
  • 54

6 Answers6

8
str = str.replace(/"|'/g, '')
Andrew
  • 8,330
  • 11
  • 45
  • 78
3
str.replace(/['"]+/g, '')
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
2

Try:

str = str.replace(new RegExp('["\']', 'g'), '');
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
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
  • 78,177
  • 11
  • 137
  • 148
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,249
  • 4
  • 40
  • 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
  • 46,442
  • 10
  • 75
  • 103