如何在js中拆分字符串,但有一些例外 [英] how to split a string in js with some exceptions

查看:234
本文介绍了如何在js中拆分字符串,但有一些例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串:

a\,bcde,fgh,ijk\,lmno,pqrst\,uv

我需要一个JavaScript函数,它将每个分割字符串,但只有那些的人才有 \ 才能

I need a JavaScript function that will split the string by every , but only those that don't have a \ before them

如何做到这一点?

推荐答案

这是我能想出的最短的事情:

Here's the shortest thing I could come up with:

'a\\,bcde,fgh,ijk\\,lmno,pqrst\\,uv'.replace(/([^\\]),/g, '$1\u000B').split('\u000B')

背后的想法是找到逗号没有前缀为反斜杠的每个地方,用字符串替换那些不常见的字符串,然后用 uncommon string。

The idea behind is to find every place where comma isn't prefixed with a backslash, replace those with string that is uncommon to come up in your strings and then split by that uncommon string.

请注意,逗号之前的反斜杠必须使用其他反斜杠转义。否则,javascript将表单 \,视为转义逗号并生成一个逗号!换句话说,如果你不能逃避反斜杠,javascript会看到: a \,bcde,fgh,ijk \,lmno,pqrst \,uv 这样 a,bcde,fgh,ijk,lmno,pqrst,uv

Note that backslashes before commas have to be escaped using another backslash. Otherwise, javascript treats form \, as escaped comma and produce simply a comma out of it! In other words if you won't escape the backslash, javascript sees this: a\,bcde,fgh,ijk\,lmno,pqrst\,uv as this a,bcde,fgh,ijk,lmno,pqrst,uv.

这篇关于如何在js中拆分字符串,但有一些例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆