Hướng dẫn replace quotes javascript

Assuming:

var someStr = 'He said "Hello, my name is Foo"';
console.log[someStr.replace[/['"]+/g, '']];

That should do the trick... [if your goal is to replace all double quotes].

Here's how it works:

  • ['"] is a character class, matches both single and double quotes. you can replace this with " to only match double quotes.
  • +: one or more quotes, chars, as defined by the preceding char-class [optional]
  • g: the global flag. This tells JS to apply the regex to the entire string. If you omit this, you'll only replace a single char.

If you're trying to remove the quotes around a given string [ie in pairs], things get a bit trickier. You'll have to use lookaround assertions:

var str = 'remove "foo" delimiting double quotes';
console.log[str.replace[/"[[^"]+[?="]]"/g, '$1']];
//logs remove foo delimiting quotes
str = 'remove only "foo" delimiting "';//note trailing " at the end
console.log[str.replace[/"[[^"]+[?="]]"/g, '$1']];
//logs remove only foo delimiting "

Chủ Đề