我可以从 JavaScript 中的某个单词中切出一个字符串,而不管它前面有多少个 characters/words 吗?

Can I slice a string from a certain word in JavaScript, no matter how many characters/words are preceding it?

我有两个字符串:

var string1 = "The quick brown fox jumps over the lazy dog.";

var string2 = "The sluggish, purple fox jumps over a rapid cat.";

有没有办法在这两种情况下都从“fox”中获取所有单词? split() 在这里不起作用,因为它占据了确切的位置 狐狸的第一个字母“f”。但这就是重点,如果 “fox”前面的单词长度不同,位置不同 “f”的变化?所以在任何情况下我都想要“fox”之后的所有内容, 单词是否从位置 0、2、3、5、8 等开始

将子字符串作为参数传递给 String.split() 将 return 原始字符串部分的数组,如果有的话,在该参数之前或之后。

string1.split('fox') // -> ['The quick brown ', ' jumps over the lazy dog']
string2.split('fox') // -> ['The sluggish, purple ', ' jumps over a rapid cat']

(但要注意:)

'The foxy fox jumps foxily'.split('fox') // -> ["The ", "y ", " jumps ", "ily"]

您可以使用 String#match and a Regular Expression:

var string1 = "The quick brown fox jumps over the lazy dog.";
var string2 = "The sluggish, purple fox jumps over a rapid cat.";

const regex = /\bfox\b .*/;

console.log(string1.match(regex));
console.log(string2.match(regex));

如果您不想在返回的字符串中包含 fox,您可以改用此正则表达式:

var string1 = "The quick brown fox jumps over the lazy dog.";
var string2 = "The sluggish, purple fox jumps over a rapid cat.";

const regex = /(?<=\bfox\b ).*/;

console.log(string1.match(regex));
console.log(string2.match(regex));