JavaScript 中的子字符串组合
javascriptweb developmentfront end technology更新于 2024/8/18 6:35:00
我们需要编写一个 JavaScript 函数,该函数将两个字符串作为第一个和第二个参数。我们把这两个字符串称为 str1 和 str2。该函数应该检查 str2 中是否存在子字符串组合,组合后会得到 str2。
子字符串组合的意思是,我们可以跳过字符,但必须保持从 str1 中选择的字符的顺序。
例如 −
如果输入字符串是 −
const str1 = 'desxooajmepwele'; const str2 = 'example';
那么输出应该是 −
const output = true;
因为字符串"example"可以通过从 str1 中挑选一些字符并保持其顺序来形成。
示例
其代码为 −
const str1 = 'desxooajmepwele'; const str2 = 'example'; const containsString = (str1 = '', str2 = '') => { let [foundAt, next] = [0, 0]; for(const char of str2){ next = str1.slice(foundAt).indexOf(char); if (next === - 1){ return false; }; foundAt += next + 1; }; return true; }; console.log(containsString(str1, str2));
输出
控制台中的输出将是 −
true