Reputation: 17930
I have a string like:
image.id."HashiCorp Terraform Team <[email protected]>"
AND image.label."some string"."some other string"
I want to replace all spaces with '___' just for the strings that are surrounded with quotes, so the final string will look like:
image.id."HashiCorp___Terraform___Team___<[email protected]>"
AND image.label."some___string"."some___other___string"
I've tried this:
text = text.replace(/"(\w+\s+)+/gi, function (a) {
return a.replace(' ', _delimiter);
});
But it only replaces the first space, so i get:
HashiCorp___Terraform Team <[email protected]>
.
and some___other string
I'm very bad with regexp so I'm probably doing something wrong :(
Upvotes: 1
Views: 273
Reputation: 626689
You may use a /"[^"]+"/g
regex to match substrings between two "
chars and then replace whitespace chars inside a callback method:
var text = 'image.id."HashiCorp Terraform Team <[email protected]>" \nAND image.label."some string"."some other string"';
var _delimiter = "___";
text = text.replace(/"[^"]+"/g, function (a) {
return a.replace(/\s/g, _delimiter);
});
console.log(text);
The "[^"]+"
pattern matches a "
, then 1 or more chars other than "
and then a closing "
. The a
variable holds the match value and a.replace(/\s/g, _delimiter)
replaces each single whitespace char inside the match value with the "delimiter".
Upvotes: 3