1

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 :(

2
  • Since your input looks like a programming language, here's an obligatory reminder that you cannot handle such languages with regexes alone and might be better off using a real tokenizer/parser. Commented Oct 11, 2018 at 11:43
  • @georg It's not a programming language, it's a free text string entered by a user that must follow some rules, but inside the quotes the user can put any value he wants, If you're concerned about security, the string is sanitized at the server. Commented Oct 11, 2018 at 11:49

1 Answer 1

3

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.