如何检查 JavaScript 中特定索引处整个字符串中的特定单词?
How to check specific word in whole string at specific index in the JavaScript?
我想在对象数组中处理以下场景,以检查字符串是否包含特定单词。我想确定检查单词的位置。下面是例子
let array = [
{
"val":"test1-test3"
},
{
"val":"test1-test2-test3"
},
{
"val":"test1-test4-test3"
},
{
"val":"test1-test2-test4-test3"
},
{
"val":"test1-test2"
},
{
"val":"test1-test4-test2-test3"
}
]
场景
- 我想检查字符串是否包含 test2。
- 如果字符串中包含test2,我想确定test2出现在哪个位置。
- 它可以出现在第一个和最后一个位置。
- 如果它出现在第一个(前 3 个字母)和最后一个位置(最后 3 个字母)之间,我想将该值设置为 false。
预期输出:
输出=[假,真,假,真,假,真]
let arr = [
{
val: "test1-test3",
},
{
val: "test1-test2-test3",
},
{
val: "test1-test4-test3",
},
{
val: "test1-test2-test4-test3",
},
{
val: "test1-test2",
},
{
val: "test1-test4-test2-test3",
},
];
const res = arr.map(({ val }) => {
const tests = val.split`-`;
const idx = tests.findIndex((item) => item === "test2");
return idx > 0 && idx < tests.length - 1;
});
console.log("res", res);
你可以使用 reduce:
let array = [{
"val": "test1-test3"
}, {
"val": "test1-test2-test3"
}, {
"val": "test1-test4-test3"
}, {
"val": "test1-test2-test4-test3"
}, {
"val": "test1-test2"
}, {
"val": "test1-test4-test2-test3"
}];
const contains = array.reduce((akku, item, index) => {
const words = item.val.split('-');
const foundIndex = words.indexOf('test2');
akku[index] = (foundIndex > 0 && foundIndex < words.length - 1);
return akku;
}, []);
console.log(contains);
我想在对象数组中处理以下场景,以检查字符串是否包含特定单词。我想确定检查单词的位置。下面是例子
let array = [
{
"val":"test1-test3"
},
{
"val":"test1-test2-test3"
},
{
"val":"test1-test4-test3"
},
{
"val":"test1-test2-test4-test3"
},
{
"val":"test1-test2"
},
{
"val":"test1-test4-test2-test3"
}
]
场景
- 我想检查字符串是否包含 test2。
- 如果字符串中包含test2,我想确定test2出现在哪个位置。
- 它可以出现在第一个和最后一个位置。
- 如果它出现在第一个(前 3 个字母)和最后一个位置(最后 3 个字母)之间,我想将该值设置为 false。
预期输出:
输出=[假,真,假,真,假,真]
let arr = [
{
val: "test1-test3",
},
{
val: "test1-test2-test3",
},
{
val: "test1-test4-test3",
},
{
val: "test1-test2-test4-test3",
},
{
val: "test1-test2",
},
{
val: "test1-test4-test2-test3",
},
];
const res = arr.map(({ val }) => {
const tests = val.split`-`;
const idx = tests.findIndex((item) => item === "test2");
return idx > 0 && idx < tests.length - 1;
});
console.log("res", res);
你可以使用 reduce:
let array = [{
"val": "test1-test3"
}, {
"val": "test1-test2-test3"
}, {
"val": "test1-test4-test3"
}, {
"val": "test1-test2-test4-test3"
}, {
"val": "test1-test2"
}, {
"val": "test1-test4-test2-test3"
}];
const contains = array.reduce((akku, item, index) => {
const words = item.val.split('-');
const foundIndex = words.indexOf('test2');
akku[index] = (foundIndex > 0 && foundIndex < words.length - 1);
return akku;
}, []);
console.log(contains);