Javascript 在大写字母前插入空格

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

Insert space before capital letters

javascriptjqueryregexstringreplace

提问by CLiown

I have a string "MySites". I want to place a space between Myand Sites.

我有一个字符串"MySites"。我想在My和之间放置一个空格Sites

How can I do this in jQuery or JavaScript?

我怎样才能在 jQuery 或 JavaScript 中做到这一点?

回答by user2051552

You can just add a space before every uppercase character and trim off the leading and trailing spaces

您可以在每个大写字符之前添加一个空格并修剪前导和尾随空格

s = s.replace(/([A-Z])/g, ' ').trim()

回答by Guffa

This will find each occurrence of a lower case character followed by an upper case character, and insert a space between them:

这将找到每个出现的小写字符后跟一个大写字符,并在它们之间插入一个空格:

s = s.replace(/([a-z])([A-Z])/g, ' ');

For special cases when 2 consecutive capital letters occur (Eg: ThisIsATest) add additional code below:

对于出现 2 个连续大写字母的特殊情况(例如:ThisIsATest),请在下面添加附加代码:

 s = s.replace(/([A-Z])([A-Z])/g, ' ');

回答by JosephGarrone

Might I suggest a slight edit to the currently accepted answer:

我是否可以建议对当前接受的答案稍作修改:

function insertSpaces(string) {
    string = string.replace(/([a-z])([A-Z])/g, ' ');
    string = string.replace(/([A-Z])([A-Z][a-z])/g, ' ')
    return string;
}

This means that:

这意味着:

ACROText -> ACRO Text
UserNameTest -> User Name Test

Which might be slightly more useful if you are dealing with db column names (And are using acronyms for some things)

如果您正在处理 db 列名,这可能会稍微有用一些(并且在某些事情上使用首字母缩略词)

回答by Devin Burke

This should insert a space between each capital letter that was not preceded by a capital letter.

这应该在前面没有大写字母的每个大写字母之间插入一个空格。

var myString = "MySites"
var newString = "";
var wasUpper = false;
for (var i = 0; i < myString.length; i++)
{
    if (!wasUpper && myString[i] == myString.toUpperCase()[i])
    {
        newString = newString + " ";
        wasUpper = true;
    }
    else
    {
        wasUpper = false;
    }
    newString = newString + myString[i];
}

newStringwill have the value you want. Also, if you want to shorten your code using regex, you can use the following code from Javascript camelCase to Regular Form

newString会有你想要的价值。此外,如果您想使用正则表达式缩短代码,您可以使用以下代码从Javascript camelCase 到正则形式

"thisStringIsGood"
    // insert a space before all caps
    .replace(/([A-Z])/g, ' ')
    // uppercase the first character
    .replace(/^./, function(str){ return str.toUpperCase(); })

回答by Adam Straughan

regex to find lower case - upper case boundary then insert a space

正则表达式找到小写 - 大写边界然后插入一个空格

<div id='x'>ThisIsMySites</div>
$('#x').text( $('#x').text().replace(/([a-z])([A-Z])/g, " ") );

http://jsfiddle.net/uXy64/

http://jsfiddle.net/uXy64/

回答by Thomas Stein

Here is what i ended up using to convert a string to a title case, based on a few of the answers here:

根据这里的一些答案,这是我最终用来将字符串转换为标题大小写的方法:

str = str
  .replace(/(_|-)/g, ' ')
  .trim()
  .replace(/\w\S*/g, function(str) {
    return str.charAt(0).toUpperCase() + str.substr(1)
  })   
  .replace(/([a-z])([A-Z])/g, ' ')
  .replace(/([A-Z])([A-Z][a-z])/g, ' ')   

Here is a JSFiddle where you can test your string to see if this meets your needs: https://jsfiddle.net/thomastasa/5236dv8t/85/

这是一个 JSFiddle,您可以在其中测试您的字符串是否满足您的需求:https://jsfiddle.net/thomastasa/5236dv8t/85/



Examples:

例子:

  • "yourStringHere" -> "Your String Here"
  • "AnotherStringHere" -> "Another String Here"
  • "someones_string" -> "Someones String"
  • "Another-String-Here" -> "Another String Here"
  • "myAWESOMEString" -> "My AWESOME String"
  • “yourStringHere”->“你的字符串在这里”
  • "AnotherStringHere" -> "这里的另一个字符串"
  • “someones_string” -> “Someones 字符串”
  • “这里的另一个字符串”->“这里的另一个字符串”
  • "myAWESOMEString" -> "我的真棒字符串"

回答by Luca Kiebel

You can use String#split()and a look-ahead for the capitalized alphabet ([A-Z]) and then Array#join()the array with a space:

您可以String#split()对大写字母 ( [A-Z]) 和Array#join()带有空格的数组使用前瞻:

let stringCamelCase = "MySites";

let string = stringCamelCase.split(/(?=[A-Z])/).join(" ");

console.log(string)

Or, as a String Object function:

或者,作为字符串对象函数:

String.prototype.cC2SC = function() {
  return this.split(/(?=[A-Z])/).join(" ");
}

console.log("MyCamelCase".cC2SC());

回答by Jose Da Silva

In a single regex replace (without trims or joins) that allows any character not just letters [a-z]or [A-Z].

在单个正则表达式中替换(没有修剪或连接),允许任何字符而不仅仅是字母[a-z][A-Z].

const str = "MySites";
str.replace(/(?<!^)([A-Z])/, " "); // -> "My Sites"

You can check more about the look behind (?<!^)here.

您可以在(?<!^)此处查看更多有关外观的信息