ScriptyChris
ScriptyChris

Reputation: 669

Replace plus, double quotes and spaces except spaces surrounded by double quotes

I have such text text + " " + getIncrementedNumber(). I want to replace to empty string the following characters via JavaScript: +, " and all spaces except that spaces, which are surounded by double quotes. Examples of input and output, which I want to achieve:

I am trying with these RegExps:

So I have a problem with excluding replacing spaces in between double quotes.

Upvotes: 0

Views: 62

Answers (2)

anubhava
anubhava

Reputation: 785128

You can use:

str = str.replace(/[+"]|[ \t]+(?=(?:(?:[^"]*"){2})*[^"]*$)/gm, '');

RegEx Demo

RegEx Breakup:

  • [+"]: Match + or :
  • |: OR
  • [ \t]+(?=(?:(?:[^"]*"){2})*[^"]*$): Match a space or tab that is outside the quotes by using a lookahead to assert even number of quotes ahead.

Upvotes: 1

trincot
trincot

Reputation: 350242

You could use

/\s*\+\s*"([^"]*)"\s*\+\s*/g

Snippet:

var s = 'text +"Lorem ipsuM"+ getIncrementedNumber()';
s = s.replace(/\s*\+\s*"([^"]*)"\s*\+\s*/g, "$1");
console.log(s);

Upvotes: 1

Related Questions