我有一个如下所示的字符串
str = "I have candy='4' and ice cream = 'vanilla'"
我想在最新的
=
左侧获取术语,并且应该获取术语,直到出现另一个 =
。所以我的字符串应该是
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]
但它查看第一个
=
并只给我左边的直接词。我怎样才能做到这一点?
注意: 如果最新的
=
左边没有 =
,我应该得到完整的字符串直到开始。 最佳答案
使用 split
和 slice
查找倒数第二个拆分组。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)
)
关于javascript - 正则表达式获取字符串直到在javascript中出现特殊字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62464728/