Replace quote characters with better ones

后端 未结 2 1746
轻奢々
轻奢々 2021-01-28 08:54

I have a webpage where I want to replace all standard quote characters \" with the nicer looking quotes. For example, we have

\"hello world\"<

相关标签:
2条回答
  • 2021-01-28 09:33

    I might be missing something obvious here, but I think the following RegEx solution would work -

    subject = 'test "abc" test "abc"';
    result = subject.replace(/"([A-Za-z ]*)"/ig, "&ldquo;$1&rdquo;");
    alert(result);
    

    If you were using PHP then you could write some similar code in PHP - (my PHP skills are somewhat lacking though! The code below was generated with RegEx Buddy so it hasn't been tested and may need changing)

    $subject = 'test "abc" test "abc"';    
    $result = preg_replace('/"([A-Za-z ]*)"/i', '&ldquo;$1&rdquo;', $subject);
    

    Alternatively, you could load the content into a DIV using PHP then use JavaScript to change the DIV contents, here's a bit of JQuery that would do the job -

    $("#contentdiv").text($("#contentdiv").text().replace(/"([A-Za-z ]*)"/ig, "&ldquo;$1&rdquo;"));
    

    There's a jsfiddle that demonstrates the above JQuery here.

    0 讨论(0)
  • 2021-01-28 09:53

    In case you have a string like test "abc" test "abc", you can check for each " whether it should be an opening or closing one by looking at how many " are preceeding it:

    If it's an even amount it should be &ldquo;, otherwise &rdquo;.

    var str = 'test "abc" test "abc"';
    var splitted = str.split('"');
    var result = '';
    for(var i = 0; i < splitted.length; i++) {
        result += splitted[i] + ( i % 2 == 0 ? '&ldqou;' : '&rdquo;' );
    }
    result = result.substring(0, result.length - 7); // remove last appended &ldquo;
    
    0 讨论(0)
提交回复
热议问题