我想在javascript中替换文本。例如,文本是: < + class abc> -
我想要结果:
<span class="operators"> < </span><span class="operators"> + </span>
<span class="keywords">class</span> abc <span class="operators"> > </span>
<span class="operators"> - </span>
Bud第二个替换规则也会替换&lt;和&gt;,以及HTML标记中的class属性。 我该如何解决这个问题?
答案 0 :(得分:0)
最基本的例子:
var operators = ["<", "+", "-", ">"],
keywords = ["class"];
"< + class abc > -".replace(/[^ ]+/g, function(m) {
if (operators.indexOf(m) > -1)
return '<span class="operators">' + m + '</span>';
else if (keywords.indexOf(m) > -1)
return '<span class="keywords">' + m + '</span>';
return m;
});
答案 1 :(得分:0)
尝试
var x = '< + class abc > -';
var array = x.split(/\s/);
var ops = /^[<>+-\/]$/;
var keywords = /^(class)$/
var result = [];
for(var i = 0; i < array.length; i++){
var item = array[i];
if(ops.test(item)) {
result.push('<span class="operators"> ' + item + ' </span>')
} else if(keywords.test(item)){
result.push('<span class="keywords"> ' + item + ' </span>')
} else {
result.push(item)
}
}
console.log(result.join(' '))
演示:Fiddle