让我说我有2个字符串:
var a = "abcdef", b = "abcdefgh";
我想找到第一个破坏完全匹配的索引,而不用遍历两个字符串并将每个字符与循环进行比较。
在此示例中,我想得到 6 ,因为 g 是破坏完整匹配的字符
答案 0 :(得分:3)
使用reduce
:
const findIndex = (a, b) => {
if (b.length > a.length)
return a.length;
a = Array.from(a);
b = Array.from(b);
const result = a.reduce((acc, cur, ind) => {
if (cur != b[ind] && (typeof acc.ind == 'undefined')) {
acc.ind = ind;
}
return acc;
}, {});
return result.ind;
}
一个例子:
let a1 = "abcdef";
let b1 = "abcdefgh";
const findIndex = (a, b) => {
if (b.length > a.length)
return a.length;
a = Array.from(a);
b = Array.from(b);
const result = a.reduce((acc, cur, ind) => {
if (cur != b[ind] && (typeof acc.ind == 'undefined')) {
acc.ind = ind;
}
return acc;
}, {});
return result.ind;
}
console.log(findIndex(a1, b1));
console.log(findIndex('aaa', ''));
console.log(findIndex('hey:)', 'hey!'));
此外,带有for
循环的版本。特别感谢@ Andreas关于如何避免if
语句的建议:
const findIndex = (a, b) => {
for (let i = 0, l = Math.max(a.length, b.length); i < l; i++) {
if (a[i] != b[i])
return i;
}
return 'equal';
}
一个例子:
let a = "abcdef";
let b = "abcdefgh";
const findIndex = (a, b) => {
for (let i = 0, l = Math.max(a.length, b.length); i < l; i++) {
if (a[i] != b[i])
return i;
}
return 'equal';
}
console.log(findIndex(a, b));
console.log(findIndex('aaa', ''));
console.log(findIndex('hey:)', 'hey!'));
答案 1 :(得分:2)
尝试一下-var index = b.indexOf(a) + a.length
var a = "abcdef", b = "abcdefgh";
document.write(b.indexOf(a) + a.length);
答案 2 :(得分:2)
在这种情况下,请尝试a.lastIndexOf(b.charAt(b.length));
var a = "abcdef", b = "abcdefgh";
document.write(a.lastIndexOf(b.charAt(b.length)));
答案 3 :(得分:1)
这是没有循环的更快解决方案-
var stringA = "abcdef",
stringB = "abcdefgh",
firstOccurrence = stringB.indexOf(stringA);
if (firstOccurrence === -1) {
alert('Search string Not found');
} else {
var stringALength = stringA.length;
document.write(firstOccurrence + stringALength);
}