我用几个例子解释我的问题:
示例1:
var str = "this is a test
and also this is a test
and this";
范围:[19 - 22]//“也”
现在我需要检查 str
从开始到 19
的位置以及从 22
到该字符串结尾的位置是否是这个字符 $
。如果存在,则返回true
,否则返回false
。在这种情况下,输出是:
false
<小时/>
示例2:
var str = "this $ is a test
and also this is a test
and this";
范围:[21 - 24]//“也”
输出:
false // there is $ before the range, but there isn't after it, so false
<小时/>
示例3:
var str = "this $ is a test
and also this is a test
and $this";
范围:[21 - 24]//“也”
输出:
true
<小时/>
示例4:
var str = "this $ is $ a test
and also this is a test
and $ this";
范围:[23 - 26]//“也”
输出:
false // there is two $ before the range and that means there isn't $ before the range, so false
<小时/>
示例5:
var str = "this $ is $ $ a test
and also this is a test
and $ this";
范围:[25 - 27]//“也”
输出:
true
<小时/>
注意:我不需要使用 indexOf()
获取该范围,我已经有了这些位置。
我怎样才能做到这一点?
最佳答案
var n= str.indexOf("also");
var pre=(str.substring(0,n).match(/\$/g) || []).length;
var post=(str.substring(n+3,str.length).match(/\$/g) || []).length;
if(pre %2 ===1 && post %2===1){
console.log(true)
} else {
console.log(false);
}
关于javascript - 如何判断某个位置是否在特定字符之间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251174/