制作某种解析功能可能更好,这取决于你的情况,就像这样。
Javascript
function wrapMarked(string, open, close) {
if (typeof string !== "string", typeof open !== "string", typeof close !== "string") {
throw new TypeError("Arguments must be strings.");
}
if ((string.match(/\^/g) || []).length % 2 !== 0) {
throw new Error("We have unmatched '^'s.");
}
string = string.replace(/\^{2}/g, "");
var index = string.indexOf("^"),
result = "",
state = true;
while (index !== -1) {
result += string.substring(0, index);
if (state) {
result += open;
} else {
result += close;
}
string = string.substring(index + 1);
index = string.indexOf("^");
state = !state;
}
return result + string;
}
var text = "Please select ^Continue^ to proceed with your call or ^Exit^ to call";
console.log(wrapMarked(text, "<font color='red'>", "</font>"));
在jsfiddle 上