【问题标题】:Compare and remove part of string比较并删除部分字符串
【发布时间】:2017-03-16 10:50:47
【问题描述】:

我有两个字符串说例子

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

我需要比较两个字符串并取出部分“前两个有明确的值,但是”

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

有没有办法用 javascript 或 jQuery 来完成这个?

【问题讨论】:

  • 添加您在 OP 中尝试过的内容
  • 我尝试使用 'match' 但它返回空值 - 请与我们分享此代码以澄清您的问题。另请参阅Find the longest common starting substring in a set of strings
  • 目的是去掉句子中重复的部分吗?
  • 实际上,我需要检索而不是删除字符串的相似部分。
  • 有没有办法用 javascript 或 jQuery 来完成这个? 是的。是内置的吗,没有。您必须自己编写一个函数

标签: javascript jquery string compare


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 你是如何得出match的?
    • 我从我理解的 OP 想要搜索的内容中得出它
    猜你喜欢
    • 1970-01-01
    • 2023-02-14
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多