Javascript 在字符串JS中查找单词的开始和结束位置

Javascript 在字符串JS中查找单词的开始和结束位置,javascript,Javascript,我有两个变量:string和word。如果存在,我需要获取字符串中单词的开始和结束位置,例如: string = "Hello world" word = "Hello" // position = [0, 4] 或 我想不出一种方法来规划这样一个函数,我认为在这种情况下没有内置函数有用,有什么想法吗?indexOf并将子字符串长度添加到找到的索引中可以得到您想要的 string=Hello world 你好 常量索引=string.indexofor

我有两个变量:string和word。如果存在,我需要获取字符串中单词的开始和结束位置,例如:

string = "Hello world"
word = "Hello"
// position = [0, 4]

我想不出一种方法来规划这样一个函数,我认为在这种情况下没有内置函数有用,有什么想法吗?

indexOf并将子字符串长度添加到找到的索引中可以得到您想要的

string=Hello world 你好 常量索引=string.indexoford; 如果索引!==-1 { const-endIndex=index+word.length-1; console.logindex,endIndex;
}仅一审
string = "hello world Hello"
word = "Hello"
// position = [0, 4]