Reputation: 669
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:
input: text + " " + getIncrementedNumber()
;
output: text getIncrementedNumber()
input: text + "WhateveR" + getIncrementedNumber()
;
output: textWhateveRgetIncrementedNumber()
input: text +"Lorem ipsuM"+ getIncrementedNumber()
;
output: textLorem ipsuMgetIncrementedNumber()
I am trying with these RegExps:
sourceText.replace( /\+|\s|\b"(.*?)\b"/g, '' )
, which results in 'text""getIncrementedNumber()'
sourceText.replace( /\+|\s|\"(.*?)\"/g, '' )
, which results in 'textgetIncrementedNumber()'
So I have a problem with excluding replacing spaces in between double quotes.
Upvotes: 0
Views: 62
Reputation: 785128
You can use:
str = str.replace(/[+"]|[ \t]+(?=(?:(?:[^"]*"){2})*[^"]*$)/gm, '');
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
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