Home > Blockchain >  Replace a String inside quotes
Replace a String inside quotes

Time:11-17

I need a Regular Expression for Javascript that replaces a string (for example >//<) if its inside any type of quotes. For example

>This is a test "With a text including // and more" for replacement<

I cant get the combination of Reg Expression rules working Im not good at that and its easy for some of you ;)

CodePudding user response:

I second @gog's answer, two regex replaces is the way to go. The outer .replace looks for quoted text, the nested .replace replaces 1 occurrences of // to \\:

const input = `This is a test "with quoted text including // and more // stuff",
"this has none",
this // is outside quotes,
and "this has one //".`

let result = input.replace(/"[^"]*"/g, m => {
  return m.replace(/\/\//g, '\\\\')
});
console.log(result);

Output:

This is a test "with quoted text including \\ and more \\ stuff",
"this has none",
this // is outside quotes,
and "this has one \\".

CodePudding user response:

This is easier with two regexes. Match quoted and non-quoted content separately and do the actual replacing in the callback function:

s = 'This "is" a // test "With a text including // and more" for "replacement"'

r = s.replace(
    /([^"] )|(". ?")/g, 
    (_, nonq, quot) => 
        nonq || quot.replace('//', 'hey'))

console.log(r)

CodePudding user response:

Important Note:

Following further research, take caution when using regex "lookaround" assertions with quantifiers. While this solution worked in my Node.js 16.14.2 environment, wider support for this feature of regex seems limited.


My Answer:

What you could use in this case are lookahead and lookbehind assertions with quantifiers. The following regex will satisfy your requirements for the actual match with the test string provided:

/(?<=").*(?=")/

Of course, since you are using JavaScript, this regex can be used with the .replace() string method to replace what the regex matches:

const testString =
  '>This is a test "With a text including // and more" for replacement<';

testString.replace(/(?<=".*)\/\/(?=.*")/, 'duck');
// >This is a test "With a text including duck and more" for replacement<

Hope this helps.

  • Related