所以我有一个看起来像这样的字符串:
var sentence = "1 is less than 2";
然后我有关键词的数组:
var array = ["is less than", "is bigger than"];
现在我想使用空格分割变量句子但忽略关键词:
var sentenceArray = ["1", "is less than" , "2"];
任何线索我该怎么办?
好的我很抱歉让这看起来像一个懒惰的问题,因此,我已经制作了一个带有分割的正则表达式,可用于匹配具有多个分隔符的句子。没什么好复杂的,但看起来很干净。享受:
var sentence = "1 is less than 2 and 3";
var sentenceArray = [];
sentenceArray = sentence.split(/(\is less than|and)/g);
alert(sentenceArray);
答案 0 :(得分:1)
你在这里。我认为你在JS中的数组是错误的。
var sentence = "1 is less than 2";
var array = ["is less than", "is bigger than"];
var result = [];
for (var i = 0; i < array.length; i++) {
if (sentence.indexOf(array[i]) > -1) {
result.push(array[i]);
var splitResults = sentence.split(array[i]);
for (var j = 0; j < splitResults.length; j++) {
result.push(splitResults[j]);
}
}
}
alert(result);
希望得到这个帮助。
答案 1 :(得分:1)
假设你的array
是字符串数组(我省略了那些花括号),你可以这样做:
var sentence = "1 is less than 2";
var array = ["is less than", "is bigger than"];
var sentenceArray = [];
for(var i in array){
var s = sentence.split(array[i]);
if(s[1]){
sentenceArray.push(s[0].trim());
sentenceArray.push(array[i]);
sentenceArray.push(s[1].trim());
break; // in case there are more than one unique delimiter in the array
}
}
console.log(sentenceArray);
输出:
["1", "is less than", "2"]
答案 2 :(得分:0)
将它们拆分为数字
var sentence = "1 is less than 2";
var sentenceArray = sentence.split(/(\d+)/g).map(function(a){return a.trim()}).filter(function(a){return a;});
document.body.innerHTML = JSON.stringify(sentenceArray);