我正在尝试用字符串中的html代码替换`ticks。
var str = "this `code` and `here`"
我的预期输出
“此代码和此处”
我想做的是下面
不确定,我无法预料到我的浏览器会挂起。和 当我调试它。我看到没有要替换的字符串的索引。
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
var pos = [];
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
pos.push(i);
}
}
if (pos.length > 1) {
for (var j = pos.length; j > 0; j--) {
var index = pos[j];
var spanHtml = '';
if (j % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
str = str.replaceAt(index, spanHtml);
}
}
答案 0 :(得分:1)
您可以将String.prototype.replace()
与RegExp
/(`\w+`)/g
带参数String.prototype.slice()
的 1, -1
用于在反引号中填充字符串
`
字符
var str = "this `code` and `here`";
var res = str.replace(/(`\w+`)/g, function(match) {
return "<span class='code'>" + match.slice(1, -1) + "</span>"
});
document.body.insertAdjacentHTML("beforeend", res);
&#13;
.code {
background: turquoise;
}
&#13;
答案 1 :(得分:0)
使用JavaScript替换方法。
var str = "this `code` and `here`";
var newStr = str.replace("`", "");
答案 2 :(得分:0)
我相信你想要这样的东西:
var str = "this `code` and `here`"
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+1);
}
var pos = [];
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
var index = i;
var spanHtml = '';
if (count % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
count++;
str = str.replaceAt(index, spanHtml);
i+= spanHtml.length -1; // correct position to account for the replacement
}
}
console.log(str)