JavaScript 通过正向后视拆分字符串

我正在尝试拆分包含分隔符的字符串,例如

  • "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 中工作?


UYOU
浏览 189回答 3
3回答

蝴蝶刀刀

我认为 Firefox 还不支持lookbehinds。相反,您可以使用捕获组进行拆分以保留定界符,匹配组内不是正斜杠的任何前面的字符,然后过滤以删除空字符串。例如: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"]

素胚勾勒不出你

我不知道为什么那个东西在其他浏览器中不起作用。但是您可以使用以下技巧replace:var text = 'a/b/c';var splitText = text&nbsp; &nbsp; .replace(new RegExp(/\//, 'g'), '/ ') // here you are replacing your leading slash `/` with slash + another symbol e.g. `/ `(space is added)&nbsp;&nbsp; &nbsp; .split(' ') // to further split with added symbol as far as they are removed when splitting.&nbsp;console.log(splitText) // ["a/", "b/", "c"]通过这种方式,您可以避免使用在 FireFox、Edge 等中不起作用的复杂正则表达式。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript