javascript - 如何判断某个位置是否在特定字符之间?

标签 javascript jquery regex string

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

示例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/

相关文章:

jquery - 如何为 Bootstrap "list-group-item"创建分页?

javascript - Symfony 3 Infinite Scroll for Announce

python - 如何精确查找和替换

python - 模式匹配检查大于符号前面是否没有小于符号

javascript - 如何识别用户输入的是 RTL 还是 LTR 语言?

javascript - XCode Instruments 在自动脚本中导出数据

javascript - 使用 jquery 按索引定位 child

JavaScript:JavaScript 什么时候评估一个函数,onload 或什么时候调用函数?

javascript - 将用户地理位置从客户端传递到服务器端

javascript - 从字符串中删除货币符号并使用 Javascript 中的单行转换为数字