【问题标题】:javascript - search(regex), get position of the last character of the matched stringjavascript - 搜索(正则表达式),获取匹配字符串的最后一个字符的位置
【发布时间】:2020-12-11 07:47:19
【问题描述】:

在 javascript 中,String.search() 返回字符的位置(字符索引)当有多个字符时在匹配开始时。例如,如果您尝试在abcdefghij 中正则表达式搜索cde,它会返回2c 所在的位置)而不是4e 所在的位置)。我该怎么做呢?我不会只占位置,加上一个固定的数字,你会得到最后一个字符(Position + 2),如果匹配有不同的长度匹配,这将不起作用。

【问题讨论】:

    标签: javascript string search


    【解决方案1】:

    请改用match。您可以使用捕获组来添加匹配的长度。

    const [, group, index] = "abcdfghij".match(/(cde?)/)
    
    /* Make sure results are not undefined */
    
    const lastIndex = index + (group.length - 1);
    

    【讨论】:

    • 伙计,有很多我没有看到的东西。不知道你可以像这样const [, group, index] 开始你的数据,那是什么?是变量、类型、数组等吗?
    • 这是数组破坏,在 ES6 中添加。如果你有一个数组[1,2,3],你可以这样做:const [one, , three] = [1,2,3]
    • 所以这个例子改变了数组中的每个元素,所以one变成1two变成2,等等。
    【解决方案2】:

    您总是可以创建自己的方法。

    function indexLastCharacter(string, search_word) {
        let indexFirstCharacter = string.search(search_word);
        return indexFirstCharacter + search_word.length;
    }
    
    console.log(indexLastCharacter("abcdefghij", "cde"))
    // -> 5
    

    【讨论】:

      【解决方案3】:

      我发现lookbehind 也可以,就像(?<=y).*$ 会在y 之后返回一个位置。

      【讨论】:

        猜你喜欢
        • 2020-09-08
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-03
        • 1970-01-01
        • 2021-06-09
        • 1970-01-01
        相关资源
        最近更新 更多