我有两个字符串说例子
str1 = "The first two have explicit values, but";
str2 = "first two have explicit values, but disabled is empty";
我需要比较两个字符串并取出部分"前两个字符串具有明确的值,但是"
我尝试使用'匹配'但它返回我的空值。
有没有办法用javascript或jQuery来实现这个目标?
答案 0 :(得分:2)
您可以在单词和其他字符组合数组上使用简单的for循环。
var str1 = "The first two have explicit values, but",
str2 = "first two have explicit values, but disabled is empty";
// split two string by word boundary
var arr1 = str1.split(/\b/),
arr2 = str2.split(/\b/);
// initialize variable for result
var str = '';
// iterate over the split array
for (var i = 0; i < arr1.length; i++) {
// check current word includes in the array and check
// the combined word is in string, then concate with str
if (arr2.includes(arr1[i]) && str2.indexOf(str + arr1[i]) > -1)
str += arr1[i];
// if string doesn't match and result length is greater
// than 0 then break the loop
else if (str.trim())
break;
}
console.log(str.trim());
答案 1 :(得分:-3)
在字符串上使用replace
:
var match = 'first two have explicit values, but ';
var str1 = 'the first two have explicit values, but';
var str2 = 'first two have explicit values, but disabled is empty';
str1.replace(match, '')
// returns 'the first two have explicit values, but'
str2.replace(match, '')
// returns 'disabled is empty'
请注意,如果字符串中有大写字母,则必须进行标准化&#39;它们,这就是为什么第一次检查实际上返回原始字符串(因为没有匹配)。我建议在字符串上使用toLowerCase
。