删除特殊符号和额外的空格,并使其成为驼峰案例javascript?

时间:2015-03-25 14:07:40

标签: javascript regex

我有这个函数来删除特殊符号和额外的空格,但是将thr字符串转换为驼峰的情况?例子

kitchener\waterloo to kitchenerWaterloo 

St. Thomas to stThomas

Owen Sound/Walkerton toowenSoundWalkerton

javascript代码

countyName.toLowerCase().replace(/[^A-Z0-9]+/ig,'');

2 个答案:

答案 0 :(得分:0)

我们可以通过将否定类转换为普通字符类来匹配我们想要的内容,然后在' em上使用Array.map

countyName = countyName.toLowerCase().match(/[A-Z0-9]+/ig).map(function(word, i){
    if(!i) return word;
    return word[0].toUpperCase() + word.slice(1); // return newly formed string
}).join("");

答案 1 :(得分:0)

您可以使用替换函数来调用要更改的字母的大写字母。

var countyName = "Owen Sound/Walkerton";
var result = countyName
    .trim()  //might need polyfill if you need to support older browsers
    .toLowerCase()  //lower case everything
    .replace(/([^A-Z0-9]+)(.)/ig, //match multiple non-letter/numbers followed by any character
        function(match) { 
            return arguments[2].toUpperCase();  //3rd index is the character we need to transform uppercase
        }
    );
    console.log(result);

现在,如果字符串前面有特殊字符,则会失败。所以trim方法需要替换为

.replace(/^[^A-Z0-9]+/gi,"")