如何将js字符串分割指定的标签组成数组

比如: 
var str = "我是/@小王@\\和/@小李@\\的好朋友"
转成
var arr = [ "我是", "/@小王@\\", "和", "/@小李@\\", "的好朋友" ]
我尝试str.split(/\/@|@\\/)得到["我是", "小王", "和", "小李", "的好朋友"]
需要保留标签和顺序用以区分,split正则标签会被去掉很困扰。
能够做到这样就更好了
var arr = [{"text": "我是"}, {"name": 小王"}, {"text": "和"}, {"name": "小李"}, {"text": "的好朋友"}]

守着星空守着你
浏览 948回答 2
2回答

元芳怎么了

其实这个问题,很简单,分析一下就知道了。分析如下:var str = "我是/@小王@\\和/@小李@\\的好朋友"你要转成var arr = [{"text": "我是"}, {"name": 小王"}, {"text": "和"}, {"name": "小李"}, {"text": "的好朋友"}]以我看来就是,通过/@和@\把字符串分割,并且以/@结尾的放到text属性中,以@\结尾的放到name中,并且保持原有顺序。既然是有两个分割字符,那么我们就分割两次。我简单写了一下,但是没有做太多检验和判断。回头你对参数做下校验。我的代码如下:var str = "我是/@小王@\\和/@小李@\\的好朋友";&nbsp; &nbsp; var strs = str.split("/@");&nbsp; &nbsp; var arr = new Array();&nbsp; &nbsp; for (var i = 0 ;i < strs.length;i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(strs[i].indexOf('@\\') != -1)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var temps = strs[i].split('@\\');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var j=0;j<temps.length;j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(j == temps.length -1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var text =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text:temps[j]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var name =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name:temps[j]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var text =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text:strs[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(name != null && '' != name && 'undifined' != name)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr.push(name);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(text != null && '' != text && 'undifined' != text)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr.push(text);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log(arr);那么,最后控制台输入如下:如果没问题,请采纳,谢谢。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript