代码之家  ›  专栏  ›  技术社区  ›  rustyx

JavaScript按正向查找拆分字符串

  •  1
  • rustyx  · 技术社区  · 5 年前

    我试着分割一个字符串,包括delimeters,所以举个例子

    • "a/b/c" ["a/", "b/", "c"]
    • "a//b" 会变成 ["a/", "/", "b"]

    var s = "a/b/c".split(/(?<=\/)/);
    
    console.log(s); // prints ["a/", "b/", "c"]

    它在Chrome中运行得非常好,但是Firefox说: SyntaxError: invalid regexp group

    1. 守则合法吗?
    2. 如何在Firefox和Edge中工作?
    1 回复  |  直到 5 年前
        1
  •  3
  •   benvc    5 年前

    let s = 'a/b/c'.split(/([^/]*\/)/).filter(x => x);
    console.log(s);
    // ["a/", "b/", "c"]

    let s = 'a//b'.split(/([^/]*\/)/).filter(x => x);
    console.log(s);
    // ["a/", "/", "b"]
        2
  •  1
  •   not-just-yeti    5 年前

    [来源: http://kangax.github.io/compat-table/es2016plus/#test-RegExp_Lookbehind_Assertions ]

    /\// "a/b//c//".split(/\//) 退货 ["a","b","","c","",""] .

    (c) 你也可以 match split )在“斜杠”上,后跟0个或更多个非斜杠: "a/b//c//".match(/[^\/]*\//g) 退货 ["a/","b/","/","c/","/"]

    顺便说一句,请确保在以“/”开头的字符串上测试您的解决方案,该字符串应该只返回 "/"

        3
  •  0
  •   Serge Olabin    5 年前

    我不知道为什么这个东西在其他浏览器中不起作用。但是你可以用下面的技巧 replace :

    var text = 'a/b/c';
    var splitText = text
        .replace(new RegExp(/\//, 'g'), '/ ') // here you are replacing your leading slash `/` with slash + another symbol e.g. `/ `(space is added) 
        .split(' ') // to further split with added symbol as far as they are removed when splitting.
     console.log(splitText) // ["a/", "b/", "c"]