代码之家  ›  专栏  ›  技术社区  ›  Mark

js regex转义引号

  •  3
  • Mark  · 技术社区  · 14 年前

    H1:

    例如:

    H1: "text here"
    

    应该变成:

    H1: "text here"
    

    我试过的东西:

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

    此外,它还应适用于其他类似文本,如:

    H1: ""text here""
    H1: "text "here""
    H1: ""text here"
    
    4 回复  |  直到 14 年前
        1
  •  0
  •   Peter Ajtai    14 年前

    然后我只对正确的行进行文本替换,在进行文本替换时,我将所有行重新连接在一起:

    <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>
    
        2
  •  1
  •   Amnon    14 年前

    请注意;引用;如果字符嵌入到HTML中,JavaScript引擎可能会用一个真正的引号替换它(编辑:当我试图在这个答案中直接写的时候,它被替换了。

        3
  •  1
  •   Anurag    14 年前

    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;");
    
        4
  •  0
  •   davidgarza davidgarza    14 年前

    试试这个:

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

    *? 匹配0个或多个前一个标记。这是一个延迟匹配,将在满足下一个标记之前匹配尽可能少的字符。

    这是我用来测试正则表达式的网站: http://gskinner.com/RegExr/