在 Javascript 中按大写拆分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10064683/
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-10-26 08:34:45  来源:igfitidea点击:

Split by Caps in Javascript

javascriptregexsplit

提问by user1294188

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

我正在尝试使用 Javascript 通过大写字母拆分字符串,

Examples of what Im trying to do:

我试图做的例子:

"HiMyNameIsBob"  ->   "Hi My Name Is Bob"
"GreetingsFriends" -> "Greetings Friends"

I am aware of the str.split()method, however I am not sure how to make this function work with capital letters.

我知道该str.split()方法,但是我不确定如何使该函数使用大写字母。

I've tried:

我试过了:

str.split("(?=\p{Upper})")

Unfortunately that doesn't work, any help would be great.

不幸的是,这不起作用,任何帮助都会很棒。

回答by Rob W

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

使用 RegExp-literals、前瞻和[A-Z]

"HiMyNameIsBob".split(/(?=[A-Z])/).join(" ");  // -> "Hi My Name Is Bob"

回答by Shiplu Mokaddim

You can use String.match to split it.

您可以使用 String.match 来拆分它。

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

回答by M3ghana

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;

回答by Ste

To expand on Rob W's answer.

扩展 Rob W 的回答。

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.

这通过添加 来检查前面的小写字符来处理任何带有缩写的句子[a-z],因此,它不会溢出任何大写字符串。

// 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);