如何找出哪个字符串插入到已知的其他字符串中?

问题描述 投票:0回答:1

我正在寻找最直接的方法来找出哪个字符串被插入到已知的其他字符串中。

这是我必须处理的事情:

  • 我有一个代表特定字符串的现有变量。例如:

var originalString = "pineapple";

  • 我还有第二个变量,表示在第二个未知字符串插入到第一个字符串中的“某处”后的原始字符串。例如:
var updatedString = "piBicycleneapple";

这是我的目标:

我需要某种方法来逆向计算哪个字符串被插入到
    originalString
  • 中以在
    updatedString
    中创建。
    
    
  • 一些例子:

如果
    originalString = "pineapple"
  • 并且如果
    updatedString = "piBicycleneapple"
    ,则所需的结果将是
    "Bicycle"
    如果 
  • originalString = "pineapple"
  • 并且如果
    updatedString = "pineapplepear"
    ,则所需的结果将是
    "pear"
    
    
  • 浏览器支持:

我正在寻找一种至少适用于当前版本的 Chrome、Firefox 和 Safari 的方法。所以这就是说,如果您偶然想分享一些花哨的最新 ECMAScript 方法来做到这一点,那不一定是破坏性的(只要 CanIUse 等可以确认该技术在现代浏览器中有效) .

其他想法:

我对此进行了一些头脑风暴,我想我也许可以使用 for 循环来逐个字符地比较

originalString

updatedString
,然后 -
某事某物 
- 利润?但我不完全确定中间部分,甚至不知道这种一般方法是否可能想得太多了?

javascript ecmascript-6 substring comparison string-comparison
1个回答
0
投票

function getNewString(originalString, updatedString) { let originalLength = originalString.length; let updatedLength = updatedString.length; // Identify the starting point where the strings start to differ let start = 0; while (start < originalLength && start < updatedLength && originalString[start] === updatedString[start]) { start++; } // Identify the ending point where the strings start to differ from the end let endOriginal = originalLength - 1; let endUpdated = updatedLength - 1; while (endOriginal >= start && endUpdated >= start && originalString[endOriginal] === updatedString[endUpdated]) { endOriginal--; endUpdated--; } // The new substring in the updatedString let newString = updatedString.substring(start, endUpdated + 1); return newString; }

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.