-2

Let's say I have this text:

const str = 'It\'s going to rain tomorrow. One observer said: "Oh my god, it\'s going to rain." We still don\'t know how much.';

What's the best way to completely remove "Oh my god, it's going to rain." from the string? Even if there are multiple quotes, just remove portions of the string that are enclosed within two quotes.

I can think of splitting it into an array and then tracking the pair and then slicing it from the array, but that's tedious and complex.

Anyone have any better idea how to solve this?

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
Mabeh Al-Zuq Yadeek
  • 46
  • 4
  • 16
  • 28

3 Answers3

1

Ignoring the fact that has been pointed out that you'd run into trouble with this string, you can use string.replace (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) in combination with regex.

In your example this could be achieved by running

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

that'd remove all occurrences of text within quotes. The result would be

It's going to rain tomorrow. One observer said:  We still don't know how much.

You might have to do some fine tuning to get the white-spaces right.

A great playground to learn and use regex is https://regexr.com/ where you can see all elements that would be found by your expression.

Tobias G.
  • 341
  • 1
  • 8
0
const str =  `It's going to rain tomorrow. One observer said: "Oh my god, it's going to rain." We still don't know how much.`;
const regex = new RegExp(/(["])(?:(?=(\\?))\2.)*?\1/g)
const replaced = str.replace(regex,'')

Output:

It's going to rain tomorrow. One observer said:  We still don't know how much. 

Regex adapted from: RegEx: Grabbing values between quotation marks

chrismclarke
  • 1,995
  • 10
  • 16
  • 2
    Why is this regex so complex? What edge cases does it account for? According to https://regex101.com/ it takes almost 10x the steps of simpler solutions. – MonkeyZeus Aug 22 '19 at 14:26
  • If your intention was to account for quoted quotes in English writing then https://writingexplained.org/how-to-quote-a-quote would be of interest. – MonkeyZeus Aug 22 '19 at 14:33
  • I think the above is better for extracting quotes including nested, so I'd say the answer from @tobias-g is better – chrismclarke Aug 22 '19 at 14:37
  • Please see the English writing link which I posted about nested quoting. The above solution seems to be geared towards handling JSON quoted quotes but in the context of JavaScript that is thoroughly unnecessary since JS has native JSON support – MonkeyZeus Aug 22 '19 at 14:43
0

You can use:

/".*?"/g

console.log( `It's going to rain tomorrow. One observer said: "Oh my god, it's going to rain." We still don't know how much.`.replace( /".*?"/g, '' ) );
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77