简体   繁体   English

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

[英]Javascript Split string on UpperCase Characters

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']

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])/);
.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"

Here you are :)给你 :)

var arr = UpperCaseArray("ThisIsTheStringToSplit");

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

This is my solution which is fast, cross-platform, not encoding dependent, and can be written in any language easily without dependencies.这是我的解决方案,它快速、跨平台、不依赖编码,并且可以轻松地用任何语言编写而无需依赖。

var s1 = "ThisЭтотΨόυτÜimunəՕրինակPříkladדוגמאΠαράδειγμαÉlda";
s2 = s1.toLowerCase();
result="";
for(i=0; i<s1.length; i++)
{
 if(s1[i]!==s2[i]) result = result +' ' +s1[i];
 else result = result + s2[i];
}
result.split(' ');

Here's an answer that handles numbers, fully lowercase parts, and multiple uppercase letters after eachother as well:这是一个处理数字、完全小写部分和多个大写字母的答案:

 const wordRegex = /[AZ]?[az]+|[0-9]+|[AZ]+(?![az])/g; const string = 'thisIsTHEString1234toSplit'; const result = string.match(wordRegex); console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM