查找两个相同字符串之间的文本

时间:2019-02-08 18:59:34

标签: javascript

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

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"
})

如果没有任何图书馆,我该怎么办? 谢谢。

3 个答案:

答案 0 :(得分:2)

这是使用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"));

答案 1 :(得分:0)

类似于下面使用RegEx的操作将获得结果,而与字符串中 Text 单词无关,从而使其更具扩展性。

正如您所说,您正在寻找单词 Text ..

var str = "rainbow Text rainbow"
var str2 = "rainbow rainbow Text rainbow rainbow"
var str3 = "rainbow rainbow rainbow Text rainbow"

getTextBetween(str,"Text")
getTextBetween(str2, "Text")
getTextBetween(str3, "Text")

function getTextBetween(str,word) {
    let pat = new RegExp(word)
    let result = pat.exec(str)
    console.log(result[0])
}

答案 2 :(得分:0)

这是一个稍微更灵活的版本:

const betweenTokens = (t1, t2 = t1) => 
  (s, i = s.indexOf(t1), j = s.indexOf(t2, i + 1)) => 
    j > -1 ? s.substring(i + t1.length, j) : ''

console.log(betweenTokens('rainbow')("rainbow Text rainbow"))
console.log(betweenTokens('<!--', '-->')("contains <!-- embedded --> comment"))

这允许您提供单独的开始和结束标记,如果开始和结束相同,则可以提供一个。它还创建了一个可重用的函数,因此您可以编写:

const betweenRainbows = betweenTokens('rainbow')
betweenRainbows('rainbow pot of gold rainbow') //=> ' pot of gold '