Javascript将unicode字符串转换为“Title Case”

时间:2012-08-13 11:40:08

标签: javascript unicode turkish pascalcasing title-case

我有一个javascript案例转换问题,由于非英文字母,我无法解决。我主要担心的是土耳其语字母。

我需要做的是:

  • hello world => Hello World
  • HELLO WORLD => Hello World
  • hELLO wOrLd => Hello World

这是我迄今为止所取得的成就:

String.prototype.turkishToUpper = function(){
    var stringlow = this;
    var letterslow = { 'i': 'İ', 'ş': 'Ş', 'ğ': 'Ğ', 'ü': 'Ü', 'ö': 'Ö', 'ç': 'Ç', 'ı': 'I' };
    stringlow = stringlow.replace(/(([iışğüçö]))/g, function(letterlow){ return letterslow[letterlow]; })
    return stringlow.toUpperCase();
}

String.prototype.turkishToLower = function(){
    var stringup = this;
    var lettersup = { 'İ': 'i', 'I': 'ı', 'Ş': 'ş', 'Ğ': 'ğ', 'Ü': 'ü', 'Ö': 'ö', 'Ç': 'ç' };
    stringup = stringup.replace(/(([İIŞĞÜÇÖ]))/g, function(letterup){ return lettersup[letterup]; })
    return stringup.toLowerCase();
}

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).turkishToUpper() + txt.substr(1).turkishToLower();});
};

但这并没有给我正确的结果,我怀疑正则表达式替换不能在unicode上使用,但是ascii。

当我使用土耳其语字符进行测试时,结果出错了。

  • şeker变成şEker而不是Şeker
  • çobanırmak成为çObanıRmak ÇobanIrmak
  • 的内容

此外,如果这可以得到解决,我需要锦上添花,不仅要用空格分隔单词,还要用其他一些停止字符分隔: - = / etc以便

  • hello-world成为Hello-World
  • 你好:世界变成你好:世界

我在这里读过许多类似的问题,但到目前为止还没有运气。

由于

注意:我认为这称为Title Case,但有些人认为它是Pascal Case。坦率地说,我有兴趣解决unicode问题(我认为是根本原因)而不是语义,所以如果我使用了错误的术语,请原谅我:)

4 个答案:

答案 0 :(得分:5)

独立功能:

function toProperCase(s){
    return s.replace(/([^\s:\-])([^\s:\-]*)/g,function($0,$1,$2){
        return $1.toUpperCase()+$2.toLowerCase();
    });
}

或者扩展String.prototype:

String.prototype.toProperCase=function() {
    return this.replace(/([^\s:\-])([^\s:\-]*)/g,function($0,$1,$2){
        return $1.toUpperCase()+$2.toLowerCase();
    });
}

"çoban ırmak becomes çOban ıRmak intead of Çoban Irmak Hello-wOrld".toProperCase();
// "Çoban Irmak Becomes Çoban Irmak Intead Of Çoban Irmak Hello-World"

<强>更新

下一代码使用自定义功能转换特定于语言环境的字符(部分测试)。代码将功能添加到String.prototypetoLocaleProperCase2toLocaleLowerCase2toLocaleUpperCase2

(function(){
    // locale specific chars
    // IMPORTANT: name of locale must be always in lower case (for "tr-TR" locale - "tr-tr") !!!
    var localeInfos={
            "tr-tr": { lower: { i:"İ", ı:"I", ş:"Ş", ğ:"Ğ", ü:"Ü", ç:"Ç", ö:"Ö" },
                       upper: { İ:"i", I:"ı", Ş:"ş", Ğ:"ğ", Ü:"ü", Ç:"ç", Ö:"ö" } }
        },
        localeInfo;
    // helper vars
    var mask="\\s:\\-", // add additional delimeters chars to the mask if needed
        rg=new RegExp("([^"+mask+"])([^"+mask+"]*)","g");
    var fnToLocaleLower=function(s){ return localeInfo.upper[s]; },
        fnToLocaleUpper=function(s){ return localeInfo.lower[s]; },
        fnToProper=function($0,$1,$2){
            if(localeInfo){
                if(localeInfo.lower.hasOwnProperty($1))$1=localeInfo.lower[$1];
                $2=$2.replace(localeInfo.upperSearchRegExp,fnToLocaleLower);
            }
            return $1.toUpperCase()+$2.toLowerCase();
        };
    // helper calculations
    var localeInfosKeys=Object.keys(localeInfos);
    for(var i=0;localeInfo=localeInfos[localeInfosKeys[i]];i++){
        localeInfo.lowerSearchRegExp=new RegExp("["+Object.keys(localeInfo.lower).join("")+"]","g");
        localeInfo.upperSearchRegExp=new RegExp("["+Object.keys(localeInfo.upper).join("")+"]","g");
    }

    // extending String.prototype
    String.prototype.toLocaleProperCase2=function toLocaleProperCase2(locale){
        localeInfo=localeInfos[arguments.length?locale.toLowerCase():null];
        return this.replace(rg,fnToProper);
    };
    String.prototype.toLocaleLowerCase2=function toLocaleLowerCase2(locale){
        return ((localeInfo=localeInfos[arguments.length?locale.toLowerCase():null]) ?
                this.replace(localeInfo.upperSearchRegExp,fnToLocaleLower):
                this).toLowerCase();
    };
    String.prototype.toLocaleUpperCase2=function toLocaleUpperCase2(locale){
        return ((localeInfo=localeInfos[arguments.length?locale.toLowerCase():null]) ?
                this.replace(localeInfo.lowerSearchRegExp,fnToLocaleUpper) :
                this).toUpperCase();
    };
})();

// testing
var sss="çoban ırmak ibecıoimes çOban ıRmak intead of Çoban IrImaİk Hello-wOrld";
console.log("Origin:    ", sss);
console.log("Proper TR: ", sss.toLocaleProperCase2("tr-TR"));
console.log("Proper:    ", sss.toLocaleProperCase2());
console.log("Lower TR:  ", sss.toLocaleLowerCase2("tr-TR"));
console.log("Lower:     ", sss.toLocaleLowerCase2());
console.log("Upper TR:  ", sss.toLocaleUpperCase2("tr-TR"));
console.log("Upper:     ", sss.toLocaleUpperCase2());

// Origin:    çoban ırmak ibecıoimes çOban ıRmak intead of Çoban IrImaİk Hello-wOrld
// Proper TR: Çoban Irmak İbecıoimes Çoban Irmak İntead Of Çoban Irımaik Hello-World
// Proper:    Çoban Irmak Ibecıoimes Çoban Irmak Intead Of Çoban Irimaik Hello-World
// Lower TR:  çoban ırmak ibecıoimes çoban ırmak intead of çoban ırımaik hello-world
// Lower:     çoban ırmak ibecıoimes çoban ırmak intead of çoban irimaik hello-world
// Upper TR:  ÇOBAN IRMAK İBECIOİMES ÇOBAN IRMAK İNTEAD OF ÇOBAN IRIMAİK HELLO-WORLD
// Upper:     ÇOBAN IRMAK IBECIOIMES ÇOBAN IRMAK INTEAD OF ÇOBAN IRIMAİK HELLO-WORLD

答案 1 :(得分:0)

这是完成这项工作的JS功能。

function toProperCase(string) {   
    output = '';
    explodedString = string.split(' '); //explode string by space
    for(var i=0;i<explodedString.length;i++){
        output += explodedString[i].charAt(0).toUpperCase() + explodedString[i].slice(1).toLowerCase()+' ';
    }
    return output.slice(0, -1);
}

答案 2 :(得分:0)

String.prototype.toProperCase = function (){
   var arr= this.toLowerCase().split(' ');
   for( var i=0;i<arr.length;i++){
      arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substr(1);
   };
   return arr.join(' ');
};

'çoban ırmak'.toProperCase() // "Çoban Irmak"

答案 3 :(得分:0)

只是另一种选择,但锦上添花:

function toProperCase( str ) {

    var i,
        j,
        chars,
        arr;

    arr = str.toLowerCase( ).split("");

    chars = {
        " " : true,
        "-" : true,
        ":" : true,
        "=" : true,
        "/" : true
    };

    for( var i = 0, j = -1; i < arr.length; i += 1, j += 1 ) {
        // if previous char (j) exists in chars and current (i) does not;
        // replace with uppercase equivalent.
        if ( ( arr[j] && chars[ arr[j] ] && !chars[ arr[i] ] ) || i === 0){
            arr[i] = arr[i].toUpperCase( );
        }
    }

    return arr.join("");
}

希望这有助于:)