繁体   English   中英

比较并删除部分字符串

[英]Compare and remove part of string

我有两个字符串说的例子

str1 = "The first two have explicit values, but";
str2 = "first two have explicit values, but disabled is empty";

我需要比较两个字符串,并取出“前两个具有显式值,但是”

我尝试使用“匹配”,但它返回了空值。

有没有办法用javascript或jQuery完成此操作?

您可以在单词和其他字符组合数组上使用简单的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()); 

在字符串上使用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'

请注意,如果字符串中有大写字母,则必须将其“规范化”,这就是为什么第一张支票实际上返回原始字符串的原因(因为没有匹配项)。 我建议为此在字符串上使用toLowerCase

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM