0

我在 XML 文件中有一个错误的字符串:summary="The name is "Rambo"。

我想"用正则表达式替换内引号,所以输出看起来像:

summary="这个名字是&quot兰博&quot。"

4

4 回答 4

1

这应该对你有用,伙计!

var outer = '"The name is "Rambo"."';
var inner = outer.replace(/^"|"$/g, '');
var final = '"' + inner.replace(/"/g, '"') + '"';
// (string) => "The name is "Rambo"."

编辑:您可以稍微简化一下,但它是不对称的,因为 JavaScript 不支持 regexp 后视

var str = '"The name is "Rambo"."';
var final = '"' + str.substr(1).replace(/"(?!$)/g, '"');
// (string) => "The name is "Rambo"."

编辑 2:使用str.slice它看起来更简单!

var str = '"The name is "Rambo"."';
var final = '"' + str.slice(1, -1).replace(/"/g, '"') + '"';
// (string) => "The name is "Rambo"."
于 2013-07-17T21:09:32.317 回答
0

这就是我的处理方式:

<script type="text/javascript">
var str = '"The name is "Rambo"."';
if(str.charAt(0)=='"' && str.charAt(str.length-1)=='"'){
    str = '"'+str.substr(1,str.length-2).replace(/"/g,"&quot;")+'"';
}
console.log(str);
</script>
于 2013-07-17T21:16:43.157 回答
0

此脚本应修复属性内的所有错误引号:

var faultyXML = '<example summary="The name is "Rambo"."/>',
    xmlString = faultyXML.replace(
        /([^"=<>\s]+)="(.+?)"(?=\s+[^"=<>\s]+="|\s*\/?>)/g,
        function(match, name, value) {
            return name+'"'+value.replace(/"/g, "&quot;")+'"';
        }
    );

正则表达式看起来很复杂但不是:-)

([^"=<>\s]+)     # group matching the attribute name. Simpler: (\w+)
="               # begin of value
(.+?)            # least number of any chars before…
"(?=             # a quote followed by
 \s+[^"=<>\s]+=" # whitespace, attribute name, equals sign and quote
 |               # or
 \s*\/?>         # the tag end
)
于 2013-07-18T13:35:19.997 回答
0

另一种正则表达式/replace解决方案

Javascript

function innerToQuot(text) {
    var last = text.length - 1;

    return text.replace(/"/g, function (character, position) {
        return (position === 0 || position === last) ? character : "&quot;";
    });
}

console.log(innerToQuot('"The name is "Rambo"."'));

输出

"The name is &quot;Rambo&quot;." 

jsfiddle

更新:根据您更新的问题。

然后解析 XML 以获取您的字符串值。

function innerToQuot(text) {
    var match = text.match(/^([^"]*)(\s*=\s*)([\s\S]*)$/),
        result = "",
        first = 0,
        last = -1;

    if (match) {
        result += match[1] + match[2];
        text = match[3];
        last += text.length;
    } else {
        first = last;
    }

    return result + text.replace(/"/g, function (character, position) {
        return (position === first || position === last) ? character : "&quot;";
    });
}

var text = 'summary="The name is "Rambo"."',
    newText = innerToQuot(text);

console.log(newText);

输出

summary="The name is &quot;Rambo&quot;." 

jsfiddle

将新字符串写回 XML

于 2013-07-17T22:40:33.170 回答