首页 > 解决方案 > 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));

因为我的解决方案需要将字符串从该位置分成两个字符串,然后将第一部分拆分为数组,将其反转并再次加入。

标签: javascript

解决方案


您可以使用正则表达式

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


推荐阅读