我有一個小程序正在檢查字符串中的字符序列對數組元素,如果在數組terms中找到了一個序列,比做某事。然而,這隻適用於我使用下面的機制在數組中的第一次實例匹配。我怎麼能讓這種情況發生多次?在jquery中替換多個字符串中的多個子字符串
實施例:terms = ['hello', 'world', 'this', 'is', 'me']
給予程序字符串是:hello here is me
程序詢問是否替換了在一個字符串中找到匹配任何的話的話紅色和綠色的數組中的字分別,但是程序停止在找到的第一個發生,也就是從當前編程的系統的結果:
'red here is me'
代替
'red here green me'
我該如何改變下面的功能來給我第二個結果?
for (var i = 0; i < terms.length && !match; i++) {
if (string.indexOf(terms[i]) > -1) {
match = true;
var newString = '';
wrapper.css("background", "#a1e4ff");
var matchString = string.substring(string.indexOf(terms[i]), (string.indexOf(terms[i]) + terms[i].length));
我不認爲你瞭解我,我不關心CSS,我關心子串替換。
這是我的當前代碼
function check(string) {
var terms = ['one', 'two'];
var match = false;
for(var i=0;i<terms.length;i++) {
if(string.indexOf(terms[i]) > -1) {
match = true;
var newString='';
var matchString = string.substring(string.indexOf(terms[i]), (string.indexOf(terms[i])+terms[i].length));
switch(matchString) {
case 'one':
newString = string.replace(matchString, "three");
break;
case 'two':
newString = string.replace(matchString, "four");
default:
alert('no matches');
}
$("ul").append("<li>" + newString + "</li>");
}
}
}
校驗(「這是二的一個實施例的字符串」);
目前我的程序的結果是: 這是
一個例如字符串我想解決我的程序導致此: 這是一個例如串四個
你是說在紅/綠之間交替出現..? – Keith