我想替换所有<
to<
和>
to >
。
我已经使用了该.replace()
功能,但它不适用于g
or gi
。
这里的例子 -http://jsfiddle.net/krishnaTORQUE/RSxnZ/1/
我想替换所有<
to<
和>
to >
。
我已经使用了该.replace()
功能,但它不适用于g
or gi
。
这里的例子 -http://jsfiddle.net/krishnaTORQUE/RSxnZ/1/
我建议:
var str = '< and >',
encoded = str.replace(/<|>/g, function(a){
return a == '<' ? '<' : '>';
});
console.log(encoded);
至于为什么你自己的尝试没有奏效,在我们看到你的尝试之前是不可能说的。
鉴于发布的链接(请注意,在您的问题中显示您的代码更有用),我建议:
function disp()
{
var text = document.getElementById('textarea').value,
output = document.getElementById('ibox');
ibox.appendChild(document.createTextNode(
text.replace(/<|>/g, function(a){
return a == '<' ? '<' : '>';
})
));
}
JS Fiddle 演示,代码仅在 Ubuntu 12.10 上的 Chromium 28 中测试。
并稍微更新以使用不显眼的 JavaScript(远离内联事件处理程序):
function disp()
{
var text = document.getElementById('textarea').value,
output = document.getElementById('ibox');
ibox.appendChild(document.createTextNode(
text.replace(/<|>/g, function(a){
return a == '<' ? '<' : '>';
})
));
}
var inputs = document.getElementsByTagName('input'),
button;
console.log(inputs);
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type == 'button' && inputs[i].value == 'click') {
button = inputs[i];
}
}
button.addEventListener('click', disp);
参考:
尝试这样的事情: -
text = text.replace(/</g, "<").replace(/>/g, ">");
使用一个正则表达式和一个函数:
var str = '< and >',
var encoded = str.replace(/(<)|(>)/g,
function(match, p1, p2)
{
if (p1) return '<';
else return '>'; // equivalent to else (p2)
})
注意使用p1
andp2
将包含带括号的子匹配 1(<)
和 2(>)
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace