将camelCaseText转换为句子案例文本

时间:2011-08-29 02:03:26

标签: javascript regex string

如何在JavaScript中将'helloThere'或'HelloThere'之类的字符串转换为'Hello There'?

23 个答案:

答案 0 :(得分:121)

var text = 'helloThereMister';
var result = text.replace( /([A-Z])/g, " $1" );
var finalResult = result.charAt(0).toUpperCase() + result.slice(1); // capitalize the first letter - as an example.

请注意" $1"中的空格。

编辑:添加了第一个字母大写的示例。当然,如果第一个字母已经是大写字母 - 您将有一个空余的空间来移除。

答案 1 :(得分:66)

或者使用lodash

lodash.startCase(str);

示例:

_.startCase('helloThere');
// ➜ 'Hello There'

Lodash是一个很好的库,可以提供许多日常js任务的快捷方式。还有许多其他类似的字符串操作函数,如camelCasekebabCase等。

答案 2 :(得分:43)

我遇到了类似的问题并按照以下方式处理:

stringValue.replace(/([A-Z]+)*([A-Z][a-z])/g, "$1 $2")

获得更强大的解决方案:

stringValue.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1")

http://jsfiddle.net/PeYYQ/

输入:

 helloThere 
 HelloThere 
 ILoveTheUSA
 iLoveTheUSA

输出:

 hello There 
 Hello There 
 I Love The USA
 i Love The USA

答案 3 :(得分:22)

没有副作用的例子。

function camel2title(camelCase) {
  // no side-effects
  return camelCase
    // inject space before the upper case letters
    .replace(/([A-Z])/g, function(match) {
       return " " + match;
    })
    // replace first char with upper case
    .replace(/^./, function(match) {
      return match.toUpperCase();
    });
}

在ES6中

const camel2title = (camelCase) => camelCase
  .replace(/([A-Z])/g, (match) => ` ${match}`)
  .replace(/^./, (match) => match.toUpperCase());

答案 4 :(得分:10)

我发现用于测试驼峰案例到标题案例函数的最佳字符串是这个荒谬的荒谬的例子,它测试了许多边缘情况。 据我所知,之前发布的所有功能都没有正确处理

ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D

这应该转换为:

及时获取您的GED关于26个ABC的歌曲是本质的但是用户456的个人ID卡在包含ABC的26A房间26次并不像C3PO或R2D2或2R2D那样容易< / em>的

如果你只想要一个处理上述情况的简单函数(以及比以前的许多答案更多的情况),这就是我写的那个。这段代码不是特别优雅或快速,但它简单易懂,易于理解。

在线可运行的示例如下:http://jsfiddle.net/q5gbye2w/56/

// Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries.
// 
// E.g.:
//    ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
//                                                  --> To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D
//    helloThere                              --> Hello There
//    HelloThere                              --> Hello There 
//    ILoveTheUSA                             --> I Love The USA
//    iLoveTheUSA                             --> I Love The USA
//    DBHostCountry                           --> DB Host Country
//    SetSlot123ToInput456                    --> Set Slot 123 To Input 456
//    ILoveTheUSANetworkInTheUSA              --> I Love The USA Network In The USA
//    Limit_IOC_Duration                      --> Limit IOC Duration
//    This_is_a_Test_of_Network123_in_12_days --> This Is A Test Of Network 123 In 12 Days
//    ASongAboutTheABCsIsFunToSing                  --> A Song About The ABCs Is Fun To Sing
//    CFDs                                    --> CFDs
//    DBSettings                              --> DB Settings
//    IWouldLove1Apple                        --> 1 Would Love 1 Apple
//    Employee22IsCool                        --> Employee 22 Is Cool
//    SubIDIn                                 --> Sub ID In
//    ConfigureCFDsImmediately                --> Configure CFDs Immediately
//    UseTakerLoginForOnBehalfOfSubIDInOrders --> Use Taker Login For On Behalf Of Sub ID In Orders
//
function camelCaseToTitleCase(in_camelCaseString) {
        var result = in_camelCaseString                         // "ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
            .replace(/([a-z])([A-Z][a-z])/g, "$1 $2")           // "To Get YourGEDIn TimeASong About The26ABCs IsOf The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times IsNot AsEasy As123ForC3POOrR2D2Or2R2D"
            .replace(/([A-Z][a-z])([A-Z])/g, "$1 $2")           // "To Get YourGEDIn TimeASong About The26ABCs Is Of The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
            .replace(/([a-z])([A-Z]+[a-z])/g, "$1 $2")          // "To Get Your GEDIn Time ASong About The26ABCs Is Of The Essence But APersonal IDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
            .replace(/([A-Z]+)([A-Z][a-z][a-z])/g, "$1 $2")     // "To Get Your GEDIn Time A Song About The26ABCs Is Of The Essence But A Personal ID Card For User456In Room26A ContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
            .replace(/([a-z]+)([A-Z0-9]+)/g, "$1 $2")           // "To Get Your GEDIn Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3POOr R2D2Or 2R2D"
            
            // Note: the next regex includes a special case to exclude plurals of acronyms, e.g. "ABCs"
            .replace(/([A-Z]+)([A-Z][a-rt-z][a-z]*)/g, "$1 $2") // "To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"
            .replace(/([0-9])([A-Z][a-z]+)/g, "$1 $2")          // "To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC 26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"  

						// Note: the next two regexes use {2,} instead of + to add space on phrases like Room26A and 26ABCs but not on phrases like R2D2 and C3PO"
            .replace(/([A-Z]{2,})([0-9]{2,})/g, "$1 $2")        // "To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
            .replace(/([0-9]{2,})([A-Z]{2,})/g, "$1 $2")        // "To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
            .trim();


  // capitalize the first letter
  return result.charAt(0).toUpperCase() + result.slice(1);
}

或者,作为user Barno suggested,如果您不介意拉入该库,使用SugarJS是一个简单的解决方案。我不确定它是否处理我上面描述的测试字符串;我还没有尝试过这个输入。

答案 5 :(得分:9)

这是我的版本。它在每个UpperCase英文字母之前添加一个空格,该字母在小写英文字母后面,并且如果需要也将第一个字母大写:

例如:
thisIsCamelCase - &gt;这是骆驼案
这是IsCamelCase - &gt;这是骆驼案
thisIsCamelCase123 - &gt;这是Camel Case123

  function camelCaseToTitleCase(camelCase){
    if (camelCase == null || camelCase == "") {
      return camelCase;
    }

    camelCase = camelCase.trim();
    var newText = "";
    for (var i = 0; i < camelCase.length; i++) {
      if (/[A-Z]/.test(camelCase[i])
          && i != 0
          && /[a-z]/.test(camelCase[i-1])) {
        newText += " ";
      }
      if (i == 0 && /[a-z]/.test(camelCase[i]))
      {
        newText += camelCase[i].toUpperCase();
      } else {
        newText += camelCase[i];
      }
    }

    return newText;
  }

答案 6 :(得分:7)

好的,我已经晚了几年,但我有一个类似的问题,我想为每一个可能的输入制作一个替代解决方案。我必须在this线程中将@ZenMaster的大部分功劳归功于@Benjamin Udink ten Cate。 这是代码:

var camelEdges = /([A-Z](?=[A-Z][a-z])|[^A-Z](?=[A-Z])|[a-zA-Z](?=[^a-zA-Z]))/g;
var textArray = ["lowercase",
                 "Class",
                 "MyClass",
                 "HTML",
                 "PDFLoader",
                 "AString",
                 "SimpleXMLParser",
                 "GL11Version",
                 "99Bottles",
                 "May5",
                 "BFG9000"];
var text;
var resultArray = [];
for (var i = 0; i < a.length; i++){
    text = a[i];
    text = text.replace(camelEdges,'$1 ');
    text = text.charAt(0).toUpperCase() + text.slice(1);
    resultArray.push(text);
}

它有三个子句,都使用lookahead来阻止正则表达式引擎消耗太多字符:

  1. [A-Z](?=[A-Z][a-z])查找大写字母,后跟大写字母,然后是小写字母。这是为了结束像美国这样的缩写词。
  2. [^A-Z](?=[A-Z])查找非大写字母后跟大写字母。这样就结束了像myWord这样的词和像99Bottles这样的符号。
  3. [a-zA-Z](?=[^a-zA-Z])寻找一封字母,后跟非字母。这样可以在像BFG9000这样的符号之前结束单词。
  4. 这个问题是我搜索结果的首位,所以希望我可以节省一些时间!

答案 7 :(得分:6)

此实现考虑连续的大写字母和数字。

function camelToTitleCase(str) {
  return str
    .replace(/[0-9]{2,}/g, match => ` ${match} `)
    .replace(/[^A-Z0-9][A-Z]/g, match => `${match[0]} ${match[1]}`)
    .replace(/[A-Z][A-Z][^A-Z0-9]/g, match => `${match[0]} ${match[1]}${match[2]}`)
    .replace(/[ ]{2,}/g, match => ' ')
    .replace(/\s./g, match => match.toUpperCase())
    .replace(/^./, match => match.toUpperCase())
    .trim();
}

// ----------------------------------------------------- //

var testSet = [
    'camelCase',
    'camelTOPCase',
    'aP2PConnection',
    'superSimpleExample',
    'aGoodIPAddress',
    'goodNumber90text',
    'bad132Number90text',
];

testSet.forEach(function(item) {
    console.log(item, '->', camelToTitleCase(item));
});

预期输出:

camelCase -> Camel Case
camelTOPCase -> Camel TOP Case
aP2PConnection -> A P2P Connection
superSimpleExample -> Super Simple Example
aGoodIPAddress -> A Good IP Address
goodNumber90text -> Good Number 90 Text
bad132Number90text -> Bad 132 Number 90 Text

答案 8 :(得分:3)

您可以使用以下功能:

function fixStr(str) {
    var out = str.replace(/^\s*/, "");  // strip leading spaces
    out = out.replace(/^[a-z]|[^\s][A-Z]/g, function(str, offset) {
        if (offset == 0) {
            return(str.toUpperCase());
        } else {
            return(str.substr(0,1) + " " + str.substr(1).toUpperCase());
        }
    });
    return(out);
}

"hello World" ==> "Hello World"
"HelloWorld" ==> "Hello World"
"FunInTheSun" ==? "Fun In The Sun"

代码中包含一堆测试字符串:http://jsfiddle.net/jfriend00/FWLuV/

在此处保留前导空格的备用版本:http://jsfiddle.net/jfriend00/Uy2ac/

答案 9 :(得分:3)

如果您处理的是 Capital Camel Case ,则此代码段可以为您提供帮助,并且其中包含一些规范,因此您可以确保它与您的案例相匹配。

export const fromCamelCaseToSentence = (word) =>
  word
    .replace(/([A-Z][a-z]+)/g, ' $1')
    .replace(/([A-Z]{2,})/g, ' $1')
    .replace(/\s{2,}/g, ' ')
    .trim();

规格:

describe('fromCamelCaseToSentence', () => {
 test('does not fall with a single word', () => {
   expect(fromCamelCaseToSentence('Approved')).toContain('Approved')
   expect(fromCamelCaseToSentence('MDA')).toContain('MDA')
 })

 test('does not fall with an empty string', () => {
   expect(fromCamelCaseToSentence('')).toContain('')
 })

 test('returns the separated by space words', () => {
   expect(fromCamelCaseToSentence('NotApprovedStatus')).toContain('Not Approved Status')
   expect(fromCamelCaseToSentence('GDBState')).toContain('GDB State')
   expect(fromCamelCaseToSentence('StatusDGG')).toContain('Status DGG')
 })
})

答案 10 :(得分:3)

基于以上示例之一,我想到了这一点:

const camelToTitle = (camelCase) => camelCase
  .replace(/([A-Z])/g, (match) => ` ${match}`)
  .replace(/^./, (match) => match.toUpperCase())
  .trim()

它对我有用,因为它使用.trim()来处理首字母大写的小写情况,最终您会得到一个多余的前导空格。

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

答案 11 :(得分:2)

试试这个图书馆

http://sugarjs.com/api/String/titleize

'man from the boondocks'.titleize()>"Man from the Boondocks"
'x-men: the last stand'.titleize()>"X Men: The Last Stand"
'TheManWithoutAPast'.titleize()>"The Man Without a Past"
'raiders_of_the_lost_ark'.titleize()>"Raiders of the Lost Ark"

答案 12 :(得分:2)

这适用于我查看

  

CamelcaseToWord( “MYNAME”); //返回我的名字

    function CamelcaseToWord(string){
      return string.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1");
    }

答案 13 :(得分:2)

另一种基于RegEx的解决方案。

respace(str) {
  const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g;
  return str.replace(regex, '$& ');
}

说明

上述RegEx由两个相似的部分组成,并由 OR 运算符分隔。前半部分:

  1. ([A-Z])-匹配大写字母...
  2. (?=[A-Z][a-z])-依次是大写和小写字母。

应用于序列 FOo 时,它会有效地匹配其 F 字母。

或者第二种情况:

  1. ([a-z])-匹配小写字母...
  2. (?=[A-Z])-后跟一个大写字母。

应用于序列 barFoo 时,它会有效地匹配其 r 字母。

找到所有替换候选者后,最后要做的是用相同的字母替换它们,但使用附加的空格字符。为此,我们可以使用'$& '作为替代,它将解析为匹配的子字符串,后跟一个空格字符。

示例

const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g
const testWords = ['ACoolExample', 'fooBar', 'INAndOUT', 'QWERTY', 'fooBBar']

testWords.map(w => w.replace(regex, '$& '))
->(5) ["A Cool Example", "foo Bar", "IN And OUT", "QWERTY", "foo B Bar"]

答案 14 :(得分:1)

我没有尝试过所有人的回答,但我修改的几个解决方案并不符合我的所有要求。

我能够想出一些确实......

的东西
export const jsObjToCSSString = (o={}) =>
    Object.keys(o)
          .map(key => ({ key, value: o[key] }))
          .map(({key, value}) =>
              ({
                key: key.replace( /([A-Z])/g, "-$1").toLowerCase(),
                value
              })
          )
          .reduce(
              (css, {key, value}) => 
                  `${css} ${key}: ${value}; `.trim(), 
              '')

答案 15 :(得分:1)

使用 JS 的 String.prototype.replace()String.prototype.toUpperCase()

const str = "thisIsATestString";
const res = str.replace(/^[a-z]|[A-Z]/g, (c, i) => (i? " " : "") + c.toUpperCase());

console.log(res);  // "This Is A Test String"

答案 16 :(得分:1)

输入 javaScript

输出 Java脚本

   var text = 'javaScript';
    text.replace(/([a-z])([A-Z][a-z])/g, "$1 $2").charAt(0).toUpperCase()+text.slice(1).replace(/([a-z])([A-Z][a-z])/g, "$1 $2");

答案 17 :(得分:1)

我认为只需使用reg exp /([a-z]|[A-Z]+)([A-Z])/g和替换"$1 $2"即可完成。

ILoveTheUSADope->我爱美国涂料

答案 18 :(得分:1)

下面是使用正则表达式演示骆驼式案例字符串到句子字符串的链接。

输入

myCamelCaseSTRINGToSPLITDemo

输出

my Camel Case STRING To SPLIT Demo


这是用于将骆驼案转换为句子文本的正则表达式

(?=[A-Z][a-z])|([A-Z]+)([A-Z][a-rt-z][a-z]\*)

$1 $2作为替代。

Click to view the conversion on regex

答案 19 :(得分:1)

上述答案都不适合我,所以不得不自带自行车:

function camelCaseToTitle(camelCase) {
    if (!camelCase) {
        return '';
    }

    var pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.substr(1);
    return pascalCase
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
        .replace(/([a-z])([0-9])/gi, '$1 $2')
        .replace(/([0-9])([a-z])/gi, '$1 $2');
}

测试用例:

null => ''
'' => ''
'simpleString' => 'Simple String'
'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside'
'stringWithNumber123' => 'String With Number 123'
'complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc'

答案 20 :(得分:0)

秘密C程序员。如果像我一样,您想保留首字母缩写词,并且不想看神秘的模式,那么也许您可能会这样:

function isUpperCase (str) {
  return str === str.toUpperCase()
}

export function camelCaseToTitle (str) {
  for (let i = str.length - 1; i > 0; i--) {
    if (!isUpperCase(str[i - 1]) && isUpperCase(str[i])) {
      str = str.slice(0, i) + ' ' + str.slice(i)
    }
  }
  return str.charAt(0).toUpperCase() + str.slice(1)
}

答案 21 :(得分:0)

对于连续大写的单词最兼容的答案是:

var text = 'theKD';
var result = text.replace(/([A-Z]{1,})/g, " $1");
var finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);

• 它还与“The KD”兼容,并且不会将其转换为“The KD”。

答案 22 :(得分:-1)

在对上述一些想法不满意之后,添加另一个我更喜欢的ES6解决方案。

https://codepen.io/902Labs/pen/mxdxRv?editors=0010#0

const camelize = (str) => str
    .split(' ')
    .map(([first, ...theRest]) => (
        `${first.toUpperCase()}${theRest.join('').toLowerCase()}`)
    )
    .join(' ');