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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7888238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:57:29  来源:igfitidea点击:

Javascript Split string on UpperCase Characters

javascript

提问by Nicholas Murray

How do you split a string into an array in Javascript by UpperCase character?

你如何通过大写字符将字符串拆分为Javascript中的数组?

So I wish to split:

所以我想拆分:

'ThisIsTheStringToSplit'

into

进入

('This', 'Is', 'The', 'String', 'To', 'Split')

回答by Teneff

I would do this with .match()like this:

我会这样做.match()

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

it will make an array like this:

它将创建一个这样的数组:

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

edit:since the string.split()method also supports regex it can be achieved like this

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

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

that will also solve the problem from the comment:

这也将解决评论中的问题:

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

回答by Max

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

This should handle the numbers as well.. the join at the end results in concatenating all the array items to a sentence if that's what you looking for

这也应该处理数字..最后的连接会导致将所有数组项连接成一个句子,如果这就是你要找的

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

Output

输出

"This Is The String To Split"

回答by Manuel van Rijn

Here you are :)

这个给你 :)

var arr = UpperCaseArray("ThisIsTheStringToSplit");

function UpperCaseArray(input) {
    var result = input.replace(/([A-Z]+)/g, ",").replace(/^,/, "");
    return result.split(",");
}