我用几个例子解释我的问题:

范例1:

var str = "this is a test
           and also this is a test
           and this";


范围:[19 - 22] // "also"

现在,我需要从str的开始直到位置以及从该字符串的19到结束为止检查22是否是此字符$。如果存在,则返回true,否则返回false。在这种情况下,输出为:

false




范例2:

var str = "this $ is a test
           and also this is a test
           and this";


范围:[21 - 24] // "also"

输出:

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] // "also"

输出:

true




范例4:

var str = "this $ is $ a test
           and also this is a test
           and $ this";


范围:[23 - 26] // "also"

输出:

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] // "also"

输出:

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);
}

07-24 15:28