Split by Caps in Javascript

前端 未结 4 1462
说谎
说谎 2020-12-01 11:57

I am trying to split up a string by caps using Javascript,

Examples of what Im trying to do:

\"HiMyNameIsBob\"  ->   \"Hi My Name Is Bob\"
\"Greet         


        
相关标签:
4条回答
  • 2020-12-01 12:16

    Use RegExp-literals, a look-ahead and [A-Z]:

    console.log(
      // -> "Hi My Name Is Bob"
      window.prompt('input string:', "HiMyNameIsBob").split(/(?=[A-Z])/).join(" ")  
    )

    0 讨论(0)
  • 2020-12-01 12:16

    To expand on Rob W's answer.

    This takes care of any sentences with abbreviations by checking for preceding lower case characters by adding [a-z], therefore, it doesn't spilt any upper case strings.

    // Enter your code description here
     var str = "THISSentenceHasSomeFunkyStuffGoingOn. ABBREVIATIONSAlsoWork.".split(/(?=[A-Z][a-z])/).join(" ");  // -> "THIS Sentence Has Some Funky Stuff Going On. ABBREVIATIONS Also Work."
     console.log(str);

    0 讨论(0)
  • 2020-12-01 12:18

    You can use String.match to split it.

    "HiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g) 
    // output 
    // ["Hi", "My", "Name", "Is", "Bob"]
    

    If you have lowercase letters at the beginning it can split that too. If you dont want this behavior just use + instead of * in the pattern.

    "helloHiMyNameIsBob".match(/[A-Z]*[^A-Z]+/g) 
    // Output
    ["hello", "Hi", "My", "Name", "Is", "Bob"]
    
    0 讨论(0)
  • 2020-12-01 12:34

    The solution for a text which starts from the small letter -

    let value = "getMeSomeText";
    let newStr = '';
        for (var i = 0; i < value.length; i++) {
          if (value.charAt(i) === value.charAt(i).toUpperCase()) {
            newStr = newStr + ' ' + value.charAt(i)
          } else {
            (i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
          }
        }
        return newStr;
    
    0 讨论(0)
提交回复
热议问题