Search code examples
javascriptregexlookbehind

js regex escaping quotes


I want to escape all quotes that comes only after the text H1:

For instance, :

H1: "text here"

should become:

H1: "text here"

This would be easy with lookbehind, but that's not in JS.

something I tried:

.replace(/H1:(.*)(")(.*)/ig, "H1:$1"$2")

Also it should work on other similar text like:

H1: ""text here""
H1: "text "here""
H1: ""text here"

Solution

  • First I split the string into lines. Then I only do the text replacement on the correct lines, and while I do the text replacement I concatenate all the lines back together:

    <script type="text/javascript">
      // Create a test string.
    var string='H1: "text here" \nH1: test "here" \nH2: not "this" one';
      // Split the string into lines
    array = string.split('\n');
      // Iterate through each line, doing the replacements and 
      // concatenating everything back together
    var newString = "";
    for(var i = 0; i < array.length; i++) {
          // only do replacement if line starts H1
          // /m activates multiline mode so that ^ and $ are start & end of each line
        if (array[i].match(/^H1:/m) ) {
              // Change the line and concatenate
              // I used &quote; instead of &quote; so that the changes are
              // visible with document.write
            newString += array[i].replace(/"/g, '&quote;') + '\n';    
        } else {
              // only concatenate
            newString += array[i] + '\n';
        }
    }
    document.write(newString);
    </script>