大写字符上的Javascript拆分字符串


Answers:


223

我这样做.match()是这样的:

'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+/g);

它将使像这样的数组:

['This', 'Is', 'The', 'String', 'To', 'Split']

编辑:由于该string.split()方法还支持正则表达式,因此可以这样实现

'ThisIsTheStringToSplit'.split(/(?=[A-Z])/); // positive lookahead to keep the capital letters

这也将通过注释解决问题:

"thisIsATrickyOne".split(/(?=[A-Z])/);

47
这将找不到单个大写字符。我建议以下内容: "thisIsATrickyOne".match(/([A-Z]?[^A-Z]*)/g).slice(0,-1)
andrewmu 2011年

18
.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")

这也应该处理数字..如果您要查找的是最后的连接,则将所有数组项连接到一个句子

'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")

输出量

"This Is The String To Split"

太棒了。但是在以下情况下,使用此命令的任何人都应该小心:'ThisIs8TheSt3ringToSplit'.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")将输出This Is 8 The St 3 To Split,并在ring之后省略小写的string()3
暗黑破坏神

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.