首页 > 解决方案 > 在javascript中获取所选关键字之前的所有字符

问题描述

我需要获取所选关键字之前的所有字符

前任:

const str = "This is example sentence for this stack overflow question"
const searchTerm =  "stack"

需要什么

expected results = 'for this stack overflow question'

标签: javascript

解决方案


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(" "));


推荐阅读