Js regex escapes quotes

I want to avoid all quotes that appear only after text H1:

For instance,

H1: "text here"

should become:

H1: "text here"

It would be easy with lookbehind, but it is not in JS.

what i tried:

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

It should also work with other similar text, for example:

H1: ""text here""
H1: "text "here""
H1: ""text here"
+3
source share
4 answers

First, I split the line into lines. Then I only do the replacement of the text on the correct lines, and while I do the replacement of the text, I merge all the lines back:

<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>
0
source

Here is one approach:

function encodeQuotesOccuringAfter(string, substring) {
    if(string.indexOf(substring) == -1) {
        return string;
    }

    var all = string.split(substring);
    var encoded = [all.shift(), all.join(substring).replace(/"/g, "&quot;")];

    return encoded.join(substring)
}

, startAt . , , "H1:".

str.replace(/"/g, function(match, offset, string) {
    var startAt = string.indexOf("H1:");
    if(startAt != -1 && offset > startAt) {
        return "&quot;";
    }
    else {
        return '"';
    }
});

, H1: , .

str.replace(/"/g, "&quot;");
+1

, , "H1", .

, " JavaScript , HTML. (Edit: , ).

+1

:

.replace(/H1:(.*?)(")(.*?)/ig, "H1:$1&quot;$3")

*? 0 . , .

-, : http://gskinner.com/RegExr/

0

Source: https://habr.com/ru/post/1755598/


All Articles