javascript 获取特定单词后的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25639365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:47:15  来源:igfitidea点击:

Get the text after a specific word

javascript

提问by Wolf

Let say I have the following strings:

假设我有以下字符串:

var Y = "TEST"

var X = "abc 123 TEST 456 def"

I would like to get the string from X that comes after the word that specified in Y.

我想从 X 中获取 Y 中指定的单词之后的字符串。

In this example it will be:

在这个例子中,它将是:

var Z = " 456 def"

回答by VisioN

Probably the fastest way will be to use .slice, .substror .substring:

可能最快的方法是使用.slice,.substr.substring

var Z = X.slice(X.indexOf(Y) + Y.length);

However there are some other alternatives, like with regular expressions:

然而,还有一些其他的选择,比如正则表达式

var Z = X.replace(new RegExp('.*' + Y), '');

Or the one with arrays, proposed by @AustinBrunkhorstin the comments:

或者@AustinBrunkhorst在评论中提出的带有数组的方法:

var Z = X.split(Y).pop();

回答by Greg

This will get you the word 'TEST and any words that occur after'

这会让你得到“测试以及之后出现的任何词”这个词

var word = 'abc 123 TEST 456 def';

var scrubbed = words.replace(/TEST(?= )([ A-Za-z0-9])+/, 'Howdy')
// abc 123 Howdy