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"
})
如果没有任何图书馆,我怎么能做到这一点?谢谢。
解决方案
这是使用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"));
推荐阅读
- c# - 在脚本之间传递 int
- sonarqube - 在 SonarQube 中显示 0% 的覆盖率(与 Teamcity 的 .Net 项目集成)
- c# - 如何异步调用任何 c# 代码(函数、Web 引用、API 调用)?
- node.js - 如何使用猫鼬方案验证密码的长度?
- angular - 未捕获的错误:无法解析 EventsComponent (Angular) 的所有参数
- java - Spring Data JPA @Query Annotation 出现问题(SQL 语法错误)
- jvm - 如何使用 Micrometer 和 Alertmanager 在 Prometheus 中提醒 JVM 内存使用情况
- javascript - 在 IE 和 Edge 上不记得 Cookie
- excel - 调整大小和移动图表源范围 VBA
- deck.gl - React 中带有控制器按钮的基本 DeckGL 地图