javascript - javascript如何确定给定位置的字符串字符是否被括号包裹
问题描述
有没有办法检查给定位置的字符串字符是否被括号包裹?也就是说不使用这个:
const string = "I hope to see a living Tasmanian wolf (thylacine)";
function isWrapped(pos) {
return string.slice(0, pos).split('').reverse().join().indexOf('(') !== -1 && string.slice(pos + 1).indexOf(')') !== -1;
}
console.log(isWrapped(40));
console.log(isWrapped(4));
因为我的解决方案需要将字符串从该位置分成两个字符串,然后将第一部分拆分为数组,将其反转并再次加入。
解决方案
您可以使用正则表达式
var regExp = /\(([^)]+)\)/;
var string = "I hope to see a living Tasmanian wolf (thylacine)"
var matches = regExp.exec(string);
//matches[1] contains the value between the parentheses
console.log(string.indexOf(matches[1]));
function checkPos(str, pos){
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(str);
//matches[1] contains the value between the parentheses
if(str.indexOf(matches[1]) == pos){
return true
}else return false
}
var string = "I hope to see a living Tasmanian wolf (thylacine)"
console.log(checkPos(string, 40))
推荐阅读
- c++ - 当前实例化成员和未知特化成员的名称查找
- node.js - Google node sdk Calendar freebusy查询不返回私人日历的时间
- python - 如何在Python中的字典项列表中按值删除重复的字典项
- vue.js - 根据计算属性的结果显示不同颜色的文本?
- nginx - X-Forwarded-For 标头不存储真实 ip 但具有 nginx ip
- javascript - 类语法中的“get”方法返回未定义
- r - 如何使用 levelplot (LatticeExtra) 在单个地图中绘制其他字段?
- android - 使用 OneTimeWorkRequest 暂停 MediaBrowserServiceCompat 音频
- lua - WoW - 为修饰键添加事件处理程序 - kgPanels
- python - 在循环中使用轴 = 1 连接数据帧/系列