Javascript Split string on UpperCase Characters

后端 未结 4 1793
后悔当初
后悔当初 2020-12-02 05:58

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

So I wish to split:

\'ThisIsTheStringToSplit\'

into <

相关标签:
4条回答
  • 2020-12-02 06:24

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

    '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

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

    that will also solve the problem from the comment:

    "thisIsATrickyOne".split(/(?=[A-Z])/);
    
    0 讨论(0)
  • 2020-12-02 06:36

    Here you are :)

    var arr = UpperCaseArray("ThisIsTheStringToSplit");
    
    function UpperCaseArray(input) {
        var result = input.replace(/([A-Z]+)/g, ",$1").replace(/^,/, "");
        return result.split(",");
    }
    
    0 讨论(0)
  • 2020-12-02 06:40
    .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"
    
    0 讨论(0)
  • 2020-12-02 06:43

    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(' ');
    
    0 讨论(0)
提交回复
热议问题