也许这样的事情应该给你一个开始(如果你真的必须)。
Javascript
var words = ["select", "update", "count"];
function modify(text) {
words.forEach(function (word) {
text = text.replace(new RegExp("\\b" + word + "\\b", "gi"), function(match) {
var insertAt = Math.floor(match.length / 2);
return match.slice(0, insertAt) + "~" + match.slice(insertAt);
});
});
return text;
}
console.log(modify("Select an option, and we'll update you. Count. Select an option, and we'll update you."));
输出
Sel~ect an option, and we'll upd~ate you. Co~unt. Sel~ect an option, and we'll upd~ate you.
上jsfiddle
更新:优化
Javascript
var words = ["select", "update", "count"],
regexs = words.map(function (word) {
return new RegExp("\\b" + word + "\\b", "gi");
});
function modify(text) {
regexs.forEach(function (regex) {
text = text.replace(regex, function (match) {
var insertAt = Math.floor(match.length / 2);
return match.slice(0, insertAt) + "~" + match.slice(insertAt);
});
});
return text;
}
console.log(modify("Select an option, and we'll update you. Count. Select an option, and we'll update you."));
上jsfiddle