javascript - 正则表达式获取字符串,直到在 javascript 中出现特殊字符
问题描述
我有一个如下所示的字符串
str = "I have candy='4' and ice cream = 'vanilla'"
我想将术语放在 latest 的左侧,=
并且应该获取术语,直到另一个=
.
所以我的字符串应该是
leftOfEqual = "'4' and ice cream"
另一个例子
str = "I have candy='4' and ice cream = 'vanilla' and house='big'"
leftOfEqual = "'vanilla' and house"
这是我regex
目前
leftOfEqual = str.match(/\S+(?= *=)/)[0]
但它只看第一个=
,只给我左边的直接单词。
我怎样才能做到这一点?
注意:=
如果latest 左侧没有存在=
,我应该得到完整的字符串直到开始。
解决方案
使用split
andslice
查找倒数第二个拆分组。
lastIndexOf
解决方案,只从后面搜索。先找到=
,然后继续下一个=
,在它们之间切分。
str = "I have candy='4' and ice cream = 'vanilla'"
console.log(
str.split('=').slice(-2)[0]
)
console.log(
str.slice(str.lastIndexOf('=',x=str.lastIndexOf('=')-1)+1,x<-1?undefined:x)
)
str = "and ice cream = 'vanilla'"
console.log(
str.split('=').slice(-2)[0]
)
console.log(
str.slice(str.lastIndexOf('=',x=str.lastIndexOf('=')-1)+1,x<-1?undefined:x)
)
str = "I have cand'4' and ice cream 'vanilla'"
console.log(
str.split('=').slice(-2)[0]
)
console.log(
str.slice(str.lastIndexOf('=',x=str.lastIndexOf('=')-1)+1,x<-1?undefined:x)
)
推荐阅读
- json - 为什么我的 JSON 请求失败率超过 50%?
- oracle - DBD::Oracle unable to connect due to OCIEnvNlsCreate error on MacOS 10.12.6
- .net - lookup hashtable returning blank result
- cassandra - Cassandra : How to select data updated in last 30 days
- shell - Running a script that reads /etc/shadow without having to log in as root
- c# - How to play multiple sounds at once in C#
- c# - Is NLog logging supported in UWP windows 10?
- c - GTK TreeViewColumn Titles Disappear
- javascript - Sinch call recording not working
- c++ - 从“已删除函数”中获取 xmemory 错误