我需要获取所选关键字之前的所有字符
例如:
const str = "This is example sentence for this stack overflow question"
const searchTerm = "stack"
需要什么
expected results = 'for this stack overflow question'
答案 0 :(得分:1)
const str = "This is example sentence for this stack overflow question"
const searchTerm = "stack"
const strings = str.split(" ");
// if you are very sure the str `must` contains searchTerm
const idx = strings.findIndex(item => item==searchTerm);
// if you are very sure the idx `must` greater than 2
console.log(strings.slice(idx-2).join(" "));
答案 1 :(得分:1)
您可以分割字符串,然后搜索搜索项的索引。如果index不等于-1,则只需对数组执行连接操作。
尝试以下方法。此外,如果搜索词之间用空格隔开,则可以使用replace()
替换搜索词。
const str = "This is example sentence for this stack overflow question"
const searchTerm = "stack overflow";
var strReplace = str.replace(searchTerm, '&&');
var strArray = strReplace.split(" ");
var index = strArray.indexOf('&&');
if(index != -1){
index = index -2 >= 0 ? index -2 : index;
var result = strArray.slice(index).join(" ").replace('&&', searchTerm);
}
console.log(result);
答案 2 :(得分:1)
您可以使用数组spilt()
,slice()
和join()
方法来实现:
let str = "This is example sentence for this stack overflow question";
let searchTerm = "stack"
function getSubstring(str){
var arrStr = str.split(' ');
var termIndex = arrStr.indexOf(searchTerm);
var res;
if(termIndex-2 > -1){
res = arrStr.slice(termIndex-2).join(' ');
} else {
res = arrStr.slice(termIndex).join(' ');
}
return res;
}
console.log(getSubstring(str));
str = "stack overflow question"
console.log(getSubstring(str));
答案 3 :(得分:1)
执行以下操作:
const str = "This is example sentence for this stack overflow question"
const searchTerm = "stack";
var strArray = str.split(" ");
var searchTermIndex = strArray.indexOf(searchTerm);
if(searchTermIndex-2 > -1){
var result= strArray.slice(searchTermIndex-2).join(" ");
console.log(result);
}