夏期劇場
夏期劇場

Reputation: 18325

Javascript (Regex): How do i replace (Backslash + Double Quote) pairs?

In Javascript, i want the below original string:

I want to replace \"this\" and \"that\" words, but NOT the one "here"

.. to become like:

I want to replace ^this^ and ^that^ words, but NOT the one "here"

I tried something like:

var str = 'I want to replace \"this\" and \"that\" words, but NOT the one "here"';
str = str.replace(/\"/g,"^");
console.log( str );

Demo: JSFiddle here.

But still .. the output is:

I want to replace ^this^ and ^that^ words, but NOT the one ^here^

Which means i wanted to replace only the \" occurrences but NOT the " alone. But i cannot.

Please help.

Upvotes: 1

Views: 4045

Answers (3)

Hin Fan Chan
Hin Fan Chan

Reputation: 1643

The problem with String.prototype.replace is that it only replaces the first occurrence without Regular Expression. To fix this, you need to add a g and the end of the RegEx, like so:

var mod = str => str.replace(/\\\"/g,'^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');

A less effective but easier to understand to do what you wanted is to split the string with the delimiter and then join it with the replacement, like so:

var mod = str => str.split('\\"').join('^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');

Note: You can wrap a string with either ' or ". Suppose your string contains ", i.e. a"a, you will need to put an \ in front of the " as "a"a" causes syntax error. 'a"a' won't cause syntax error as the parser knows the " is part of the string, but when you put a \ in front of " or any other special characters, it means the following character is a special character. So 'a\"a' === 'a"a' === "a\"a". If you want to store \, you will need to use \ regardless of the type of quote you use, so to store \", you will need to use '\\"', '\\\"' or "\\\"".

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can use RegExp /(")/, String.prototype.lastIndexOf(), String.prototype.slice() to check if matched character is last or second to last match in input string. If true, return original match, else replace match with "^" character.

var str = `I want to replace \"this\" and \"that\" words, but NOT the one "here"`;

var res = str.replace(/(")/g, function(match, _, index) {
  return index === str.lastIndexOf(match) 
         || index === str.slice(0, str.lastIndexOf(match) -1)
                      .lastIndexOf(match)
         ? match
         : "^"
});
console.log(res);

Upvotes: 1

Dinh Tran
Dinh Tran

Reputation: 614

As @adeneo's comment, your string was created wrong and not exactly like your expectation. Please try this:

var str = 'I want to replace \\"this\\" and \\"that\\" words, but not the one "here"';
str = str.replace(/\\\"/g,"^");
console.log(str);

Upvotes: 2

Related Questions