如何将camelCase转换为带空格的字符串? (例如camelCase为“Camel Case”)

时间:2012-02-23 18:21:07

标签: regex string coldfusion

使用ColdFusion,我想将camelCase字符串转换为人类可读的字符串,例如:

firstName - >名字

此外,理想情况下,这将使用Ucase(rereplace('myCamelCaseString',[regex]," "))之类的所有内联方式完成。如果内联不可能,那么UDF也许呢?

5 个答案:

答案 0 :(得分:11)

#rereplace("camelCaseString","([A-Z])"," \1","all")#

编辑:下面的版本将处理小写的第一个字符。

#rereplace(rereplace("camelCaseString","(^[a-z])","\u\1"),"([A-Z])"," \1","all")#

答案 1 :(得分:4)

CFLib是你的朋友!

除了大写之外,还有camelToSpace()可以满足您的要求。

<cfscript>
/**
 * Breaks a camelCased string into separate words
 * 8-mar-2010 added option to capitalize parsed words Brian Meloche brianmeloche@gmail.com
 * 
 * @param str      String to use (Required)
 * @param capitalize      Boolean to return capitalized words (Optional)
 * @return Returns a string 
 * @author Richard (brianmeloche@gmail.comacdhirr@trilobiet.nl) 
 * @version 0, March 8, 2010 
 */
function camelToSpace(str) {
    var rtnStr=lcase(reReplace(arguments.str,"([A-Z])([a-z])","&nbsp;\1\2","ALL"));
    if (arrayLen(arguments) GT 1 AND arguments[2] EQ true) {
        rtnStr=reReplace(arguments.str,"([a-z])([A-Z])","\1&nbsp;\2","ALL");
        rtnStr=uCase(left(rtnStr,1)) & right(rtnStr,len(rtnStr)-1);
    }
return trim(rtnStr);
}
</cfscript>

如果要将结果字符串中的每个单词大写,则为CapFirstTitle()

<cfscript>
/**
 * Returns a string with words capitalized for a title.
 * Modified by Ray Camden to include var statements.
 * Modified by James Moberg to use structs, added more words, and reset-to-all-caps list.
 * 
 * @param initText      String to be modified. (Required)
 * @return Returns a string. 
 * @author Ed Hodder (ed.hodder@bowne.com) 
 * @version 3, October 7, 2011 
 */
function capFirstTitle(initText){
       var j = 1; var m = 1;
       var doCap = true;
       var tempVar = "";
       /* Make each word in text an array variable */
       var Words = ListToArray(LCase(trim(initText)), " ");
       var excludeWords = structNew();
       var ResetToALLCAPS = structNew();
       /* Words to never capitalize */
       tempVar =  ListToArray("a,above,after,ain't,among,an,and,as,at,below,but,by,can't,don't,for,from,from,if,in,into,it's,nor,of,off,on,on,onto,or,over,since,the,to,under,until,up,with,won't");
       for(j=1; j LTE (ArrayLen(tempVar)); j = j+1){
               excludeWords[tempVar[j]] = 0;
       }
       /* Words to always capitalize */
       tempVar = ListToArray("II,III,IV,V,VI,VII,VIII,IX,X,XI,XII,XIII,XIV,XV,XVI,XVII,XVIII,XIX,XX,XXI");
       for(j=1; j LTE (ArrayLen(tempVar)); j = j+1){
               ResetToALLCAPS[tempVar[j]] = 0;
       }
       /* Check words against exclude list */
       for(j=1; j LTE (ArrayLen(Words)); j = j+1){
               doCap = true;
               /* Word must be less than four characters to be in the list of excluded words */
               if(LEN(Words[j]) LT 4){
                       if(structKeyExists(excludeWords,Words[j])){ doCap = false; }
               }
               /* Capitalize hyphenated words */
               if(ListLen(trim(Words[j]),"-") GT 1){
                       for(m=2; m LTE ListLen(Words[j], "-"); m=m+1){
                               tempVar = ListGetAt(Words[j], m, "-");
                               tempVar = UCase(Mid(tempVar,1, 1)) & Mid(tempVar,2, LEN(tempVar)-1);
                               Words[j] = ListSetAt(Words[j], m, tempVar, "-");
                       }
               }
               /* Automatically capitalize first and last words */
               if(j eq 1 or j eq ArrayLen(Words)){ doCap = true; }
               /* Capitalize qualifying words */
               if(doCap){ Words[j] = UCase(Mid(Words[j],1, 1)) & Mid(Words[j],2, LEN(Words[j])-1); }
               if (structKeyExists(ResetToALLCAPS, Words[j])) Words[j] = ucase(Words[j]);
       }
       return ArrayToList(Words, " ");
}
</cfscript>

因此,一旦你有了这些UDF,就可以做到

CapFirstTitle(camelToSpace('myCamelCaseString'))

将返回My Camel Case String

答案 2 :(得分:0)

这里有两个函数可以将一串单词转换为驼峰大小写。单词可以用空格或下划线分隔,但您可以根据需要添加其他字符。

<cffunction name="camelCase" access="public" output="false" returntype="string">
    <cfargument name="sourceString" type="string" required="true">
    <cfscript>
        var s = LCase(Trim(arguments.sourceString));
        s = camelCaseByWordSeperator(s, " ");
        s = camelCaseByWordSeperator(s, "_");   
        return s;
    </cfscript>
</cffunction>

<cffunction name="camelCaseByWordSeperator" access="private" output="false" returntype="string">
    <cfargument name="sourceString" type="string" required="true">
    <cfargument name="separator"    type="string" required="false" default="_">
    <cfscript>
        var s = arguments.sourceString;
        var wordBreakPos = Find(arguments.separator, s); 
        while (wordBreakPos gt 0) {
            lens = Len(s);
            if (wordBreakPos lt lens) {
                s = Replace(Left(s, wordBreakPos), arguments.separator, "", "all") & UCase(Mid(s, wordBreakPos+1, 1)) & Right(s, lens - wordBreakPos - 1);
            } else {
                s = Replace(s, arguments.separator, "", "all");
            }
            wordBreakPos = Find(arguments.separator, s);
        }
        return s;
    </cfscript>
</cffunction>

答案 3 :(得分:0)

自定义camalCase方法

<cfset variables.string = 'I am developer'>
<cfset variables.counter = 1>
<cfset variables.actualString = ''>
<cfloop list="#variables.string#" index="i" delimiters=" ">
    <cfif variables.counter EQ 1>
        <cfset variables.actualString = ReplaceNoCase(i, Left(variables.string, 1), Left(LCase(variables.string), 1), "ONE")>
    <cfelse>
        <cfset variables.actualString = variables.actualString &''& ucFirst(i)>
    </cfif>
    <cfset variables.counter = variables.counter + 1>
</cfloop>
<cfdump var="#variables.actualString#">
<cfabort>

enter image description here

答案 4 :(得分:-3)

我认为你不能一次性使用正则表达式,因为它们不支持递归/迭代,所以你不能使它适用于任意数量的wordsPushedTogether的字符串。

你可以做一个循环,用空字符串开头,循环遍历camelCase字符串,每次找到大写字母时,拆掉它前面的字母,然后用空格将它附加到你的新字符串。 / p>