js 字符串转数组

小丑的帽子
  • 99

如题
怎么简洁的能把str转换成strArry
???

var str = '123人(@@2972109)。'

var strArry = ["123人(", "@@2972109", ")。"]

回复
阅读 1.1k
5 个回答
✓ 已被采纳
'123人(@@2972109)。'.trim().split(/(?<=\()|(?=\))/)
// ["123人(", "@@2972109", ")。"]
var str = '123人(@@2972109)。'
var str2 = str.replace(/(\()/g,'$1,')
var str3 = str2.replace(/(\))/g,',$1')
var strArray = str3.split(",")
'123人(@@2972109)。'.split(/((?<=\()|(?=\)))/).filter(v=>!!v)

测试:

2次拆分同时保留分隔符..
split后补

var str = '123人(@@2972109)。'
let tmp1 = str.split("(")
let tmp2 = tmp1[1].split(")")

let strArr = [tmp1[0]+"(",tmp2[0],")"+tmp2[1]]

正则找子串

var str = '123人(@@2972109)。'
let matched = str.match(/^(.*)\((.*)\)(.*)$/);
let strArr = [matched[1]+"(",matched[2],")"+matched[3]];
你知道吗?

宣传栏