我在 XML 文件中有一个错误的字符串:summary="The name is "Rambo"。
我想"
用正则表达式替换内引号,所以输出看起来像:
summary="这个名字是"
兰博"
。"
我在 XML 文件中有一个错误的字符串:summary="The name is "Rambo"。
我想"
用正则表达式替换内引号,所以输出看起来像:
summary="这个名字是"
兰博"
。"
这应该对你有用,伙计!
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"."
这就是我的处理方式:
<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,""")+'"';
}
console.log(str);
</script>
此脚本应修复属性内的所有错误引号:
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, """)+'"';
}
);
正则表达式看起来很复杂但不是:-)
([^"=<>\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
)
另一种正则表达式/replace
解决方案
Javascript
function innerToQuot(text) {
var last = text.length - 1;
return text.replace(/"/g, function (character, position) {
return (position === 0 || position === last) ? character : """;
});
}
console.log(innerToQuot('"The name is "Rambo"."'));
输出
"The name is "Rambo"."
更新:根据您更新的问题。
然后解析 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 : """;
});
}
var text = 'summary="The name is "Rambo"."',
newText = innerToQuot(text);
console.log(newText);
输出
summary="The name is "Rambo"."
将新字符串写回 XML