[英]How to verify that a certain character is inside two dedicated characters in javascript?
Let's say that the character we need to target is $ , and we need to verify if it lies between two ' & ' .假设我们需要定位的字符是$ ,我们需要验证它是否位于两个' & '之间。 The code will look something like this :代码看起来像这样:
var str = " Verify '$' "
var str2 = " Let's see if ' The $ is inside ! ' "
var str3 = " I got $ "
console.log(verify(str)) //=> true
console.log(verify(str2)) //=> true
console.log(verify(str3)) //=> false
Javascript String.prototype.includes() , can be used to verify if $ exists in the string but I am not understanding how to verify if it is inside ' & ' ? Javascript String.prototype.includes()可用于验证$是否存在于字符串中,但我不明白如何验证它是否在' & ' 内?
You could look for $
, wrapped by '
.您可以查找$
,由'
包裹。
const check = string => /'.*\\$.*'/.test(string); console.log([ " Verify '$' ", " Let's see if ' The $ is inside ! ' ", " I got $ "].map(check) );
This can be done using Regular Expressions :这可以使用正则表达式来完成:
function verify(input) { const regex = RegExp(/'.*?\\$.*?'/); return regex.test(input); } var str = " Verify '$' " var str2 = " Let's see if ' The $ is inside ! ' " var str3 = " I got $ " console.log(verify(str)) //=> true console.log(verify(str2)) //=> true console.log(verify(str3)) //=> false
/'.*?\\$.*?'/
pattern description : /'.*?\\$.*?'/
模式描述:
'
matches the character '
literally (case sensitive) '
字面上匹配字符'
(区分大小写)
.*?
matches any character (except for line terminators)匹配任何字符(行终止符除外)
*?
Quantifier — Matches between zero and unlimited times , as few times as possible, expanding as needed (lazy)量词 - 在零次和无限次之间匹配,尽可能少的次数,根据需要扩展(懒惰)
\\$
matches the character $
literally (case sensitive) \\$
字面上匹配字符$
(区分大小写)
.*?
matches any character (except for line terminators)匹配任何字符(行终止符除外)
*?
Quantifier — Matches between zero and unlimited times , as few times as possible, expanding as needed (lazy)量词 - 在零次和无限次之间匹配,尽可能少的次数,根据需要扩展(懒惰)
'
matches the character '
literally (case sensitive) '
字面上匹配字符'
(区分大小写)
Its pretty hard to check if the $
is indeed between two '
and not between a pair of ' a '
and ' b 'b
.很难检查$
是否确实在两个'
之间'
而不是在一对' a '
和' b 'b
。 So I would recommend iterating through the string and toggling a boolean whenever you see a quote.因此,我建议在看到引号时遍历字符串并切换布尔值。 If you find a $
when the boolean is true
check if there is a '
in the rest of the text;如果在布尔值为true
时找到$
,请检查文本的其余部分是否有'
;
console.log(verify("'$'")) //=> true console.log(verify("' $ '")) //=> true console.log(verify("'a' $ '")) //=> false console.log(verify(" ' $ ")) //=> false function verify(text) { var openQuotes = false; for (var index = 0; index < text.length; index++) { if (text[index] === "'") openQuotes = !openQuotes; else if (text[index] === "$" && openQuotes && text.indexOf("'", index) !== -1) return true; } return false; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.