首页 > 解决方案 > 在两个相同的字符串之间查找文本

问题描述

是否有任何库可以从字符串中获取两个单词或符号之间的文本?这是我想要做的:

var string = "rainbow Text rainbow"
// I want to find "Text" because it's between the two words "rainbow"
string.getTextBetween("rainbow", function(text) {
    console.log(text) // should log "Text"
})

如果没有任何图书馆,我怎么能做到这一点?谢谢。

标签: javascript

解决方案


这是使用split(). 如果只有两个相同的,它将起作用

function getTextBetween(string,word){
    //if there word in not present in string 2 times
    if(string.indexOf(word) === string.lastIndexOf(word) || string.indexOf(word) === -1) return ''
	return string.split(word)[1].trim();
}
console.log(getTextBetween("rainbow Text rainbow text after","rainbow"));
console.log(getTextBetween("text before rainbow this is between rainbow this is not between","rainbow"));
console.log(getTextBetween("rainbo this is between rainbow this is not between","rainbow"));


推荐阅读