Sco*_*ach 145 javascript regex camelcasing
如何使用javascript正则表达式将字符串转换为驼峰大小写?
EquipmentClass name或者
Equipment className或equipment class name或Equipment Class Name
应该都成为:equipmentClassName.
CMS*_*CMS 208
查看代码,只需两次replace调用即可实现:
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
return index == 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
camelize("EquipmentClass name");
camelize("Equipment className");
camelize("equipment class name");
camelize("Equipment Class Name");
// all output "equipmentClassName"
Run Code Online (Sandbox Code Playgroud)
编辑:或者只需一次replace调用,也可以捕获白色空格RegExp.
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
Run Code Online (Sandbox Code Playgroud)
d4n*_*yll 80
如果有人使用lodash,则有一个_.camelCase()功能.
_.camelCase('Foo Bar');
// ? 'fooBar'
_.camelCase('--foo-bar--');
// ? 'fooBar'
_.camelCase('__FOO_BAR__');
// ? 'fooBar'
Run Code Online (Sandbox Code Playgroud)
Sco*_*ach 47
我刚结束这样做:
String.prototype.toCamelCase = function(str) {
return str
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
Run Code Online (Sandbox Code Playgroud)
我试图避免将多个替换语句链接在一起.我的功能中有1美元,2美元,3美元的东西.但是这种类型的分组很难理解,你提到的跨浏览器问题也是我从未想过的.
ism*_*iet 39
您可以使用此解决方案:
function toCamelCase(str){
return str.split(' ').map(function(word,index){
// If it is the first word make sure to lowercase all the chars.
if(index == 0){
return word.toLowerCase();
}
// If it is not the first word only upper case the first char and lowercase the rest.
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join('');
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*ric 26
在斯科特的具体案例中,我会选择以下内容:
String.prototype.toCamelCase = function() {
return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
'EquipmentClass name'.toCamelCase() // -> equipmentClassName
'Equipment className'.toCamelCase() // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName
Run Code Online (Sandbox Code Playgroud)
正则表达式将匹配第一个字符(如果它以大写字母开头)和任何字母字符后面的空格,即指定字符串中的2或3次.
通过加强正则表达式,/^([A-Z])|[\s-_](\w)/g它也将使用连字符和下划线类型名称.
'hyphen-name-format'.toCamelCase() // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
Run Code Online (Sandbox Code Playgroud)
smi*_*ace 25
为了得到ç黄褐色的Ç ASE
ES5
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
Run Code Online (Sandbox Code Playgroud)
ES6
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}
Run Code Online (Sandbox Code Playgroud)
为了获得ç黄褐色的小号 entence ç ASE或P ASCAL Ç ASE
var camelSentence = function camelSentence(str) {
return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
Run Code Online (Sandbox Code Playgroud)
注意:
对于带有重音符号的语言。确实包含À-ÖØ-öø-ÿ以下正则表达式
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g
Eil*_*idh 21
function toCamelCase(str) {
// Lower cases the string
return str.toLowerCase()
// Replaces any - or _ characters with a space
.replace( /[-_]+/g, ' ')
// Removes any non alphanumeric characters
.replace( /[^\w\s]/g, '')
// Uppercases the first character in each group immediately following a space
// (delimited by spaces)
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
// Removes spaces
.replace( / /g, '' );
}
Run Code Online (Sandbox Code Playgroud)
我试图找到一个camelCase字符串的JavaScript函数,并希望确保删除特殊字符(我无法理解上面的一些答案正在做什么).这是基于cc young的回答,添加了评论并删除了$ peci&l字符.
vit*_*y-t 18
可靠的高性能示例:
function camelize(text) {
text = text.replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
return text.substr(0, 1).toLowerCase() + text.substr(1);
}
Run Code Online (Sandbox Code Playgroud)
大小写变化字符:
-_.如果不需要正则表达式,你可能想看看下面的代码我做了一个很久以前的星星:
String.prototype.toUpperCaseFirstChar = function() {
return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}
String.prototype.toLowerCaseFirstChar = function() {
return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}
String.prototype.toUpperCaseEachWord = function( delim ) {
delim = delim ? delim : ' ';
return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}
String.prototype.toLowerCaseEachWord = function( delim ) {
delim = delim ? delim : ' ';
return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}
Run Code Online (Sandbox Code Playgroud)
我没有进行任何性能测试,regexp版本可能会或可能不会更快.
这个函数绕过了cammelcase这样的测试
Foo Bar--foo-bar--__FOO_BAR__-foo123Barfoo_Barfunction toCamelCase(str)
{
var arr= str.match(/[a-z]+|\d+/gi);
return arr.map((m,i)=>{
let low = m.toLowerCase();
if (i!=0){
low = low.split('').map((s,k)=>k==0?s.toUpperCase():s).join``
}
return low;
}).join``;
}
console.log(toCamelCase('Foo Bar'));
console.log(toCamelCase('--foo-bar--'));
console.log(toCamelCase('__FOO_BAR__-'));
console.log(toCamelCase('foo123Bar'));
console.log(toCamelCase('foo_Bar'));
console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase('Equipment Class Name'));Run Code Online (Sandbox Code Playgroud)
为了有效地创建一个将字符串的大小写转换为驼峰式大小写的函数,该函数还需要先将每个字符串转换为小写字母,然后再将非第一个字符串的第一个字符的大小写转换为大写字母。
\n我的示例字符串是:
\n"text That I WaNt to make cAMEL case"\nRun Code Online (Sandbox Code Playgroud)\n针对此问题提供的许多其他解决方案都会返回以下内容:
\n"textThatIWaNtToMakeCAMELCase"\nRun Code Online (Sandbox Code Playgroud)\n不过,我认为所需的输出是这样的,其中所有中间字符串大写字符首先转换为小写:
\n"textThatIWantToMakeCamelCase"\nRun Code Online (Sandbox Code Playgroud)\nreplace()这可以在不使用任何方法调用的情况下通过利用String.prototype.split()、Array.prototype.map()和Array.prototype.join()方法来完成:
function makeCamelCase(str) {\n return str\n .split(\' \')\n .map((e,i) => i\n ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()\n : e.toLowerCase()\n )\n .join(\'\')\n}\n\nmakeCamelCase("text That I WaNt to make cAMEL case")\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\nRun Code Online (Sandbox Code Playgroud)\n我将分解每一行的作用,然后以另外两种格式\xe2\x80\x94 ES6 和方法提供相同的解决方案String.prototype,尽管我建议不要像这样直接扩展内置 JavaScript 原型。
function makeCamelCase(str) {\n return str\n // split string into array of different words by splitting at spaces\n .split(\' \')\n // map array of words into two different cases, one for the first word (`i == false`) and one for all other words in the array (where `i == true`). `i` is a parameter that denotes the current index of the array item being evaluated. Because indexes start at `0` and `0` is a "falsy" value, we can use the false/else case of this ternary expression to match the first string where `i === 0`.\n .map((e,i) => i\n // for all non-first words, use a capitalized form of the first character + the lowercase version of the rest of the word (excluding the first character using the slice() method)\n ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()\n // for the first word, we convert the entire word to lowercase\n : e.toLowerCase()\n )\n // finally, we join the different strings back together into a single string without spaces, our camel-cased string\n .join(\'\')\n}\n\nmakeCamelCase("text That I WaNt to make cAMEL case")\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\nRun Code Online (Sandbox Code Playgroud)\nconst makeCamelCase = str => str.split(\' \').map((e,i) => i ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : e.toLowerCase()).join(\'\')\n\nmakeCamelCase("text That I WaNt to make cAMEL case")\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\nRun Code Online (Sandbox Code Playgroud)\nString.prototype方法版本String.prototype.toCamelCase = function() {\n return this\n .split(\' \')\n .map((e,i) => i\n ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()\n : e.toLowerCase()\n )\n .join(\'\')\n}\n\n"text That I WaNt to make cAMEL case".toCamelCase()\n// -> "textThatIWantToMakeCamelCase" \xe2\x9c\x85\nRun Code Online (Sandbox Code Playgroud)\n
我的ES6方法:
const camelCase = str => {
let string = str.toLowerCase().replace(/[^A-Za-z0-9]/g, ' ').split(' ')
.reduce((result, word) => result + capitalize(word.toLowerCase()))
return string.charAt(0).toLowerCase() + string.slice(1)
}
const capitalize = str => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1)
let baz = 'foo bar'
let camel = camelCase(baz)
console.log(camel) // "fooBar"
camelCase('foo bar') // "fooBar"
camelCase('FOO BAR') // "fooBar"
camelCase('x nN foo bar') // "xNnFooBar"
camelCase('!--foo-¿?-bar--121-**%') // "fooBar121"
Run Code Online (Sandbox Code Playgroud)
最佳答案很简洁,但它不能处理所有边缘情况。对于任何需要更强大的实用程序,没有任何外部依赖项的人:
function camelCase(str) {
return (str.slice(0, 1).toLowerCase() + str.slice(1))
.replace(/([-_ ]){1,}/g, ' ')
.split(/[-_ ]/)
.reduce((cur, acc) => {
return cur + acc[0].toUpperCase() + acc.substring(1);
});
}
function sepCase(str, sep = '-') {
return str
.replace(/[A-Z]/g, (letter, index) => {
const lcLet = letter.toLowerCase();
return index ? sep + lcLet : lcLet;
})
.replace(/([-_ ]){1,}/g, sep)
}
// All will return 'fooBarBaz'
console.log(camelCase('foo_bar_baz'))
console.log(camelCase('foo-bar-baz'))
console.log(camelCase('foo_bar--baz'))
console.log(camelCase('FooBar Baz'))
console.log(camelCase('FooBarBaz'))
console.log(camelCase('fooBarBaz'))
// All will return 'foo-bar-baz'
console.log(sepCase('fooBarBaz'));
console.log(sepCase('FooBarBaz'));
console.log(sepCase('foo-bar-baz'));
console.log(sepCase('foo_bar_baz'));
console.log(sepCase('foo___ bar -baz'));
console.log(sepCase('foo-bar-baz'));
// All will return 'foo__bar__baz'
console.log(sepCase('fooBarBaz', '__'));
console.log(sepCase('foo-bar-baz', '__'));
Run Code Online (Sandbox Code Playgroud)
演示在这里:https : //codesandbox.io/embed/admiring-field-dnm4r?fontsize=14&hidenavigation=1&theme=dark
lodash可以很好地做到这一点:
var _ = require('lodash');
var result = _.camelCase('toto-ce héros')
// result now contains "totoCeHeros"
Run Code Online (Sandbox Code Playgroud)
尽管它lodash可能是一个“大”库(〜4kB),但是它包含许多您通常使用摘要或自行构建的功能。
小智 5
return "hello world".toLowerCase().replace(/(?:(^.)|(\s+.))/g, function(match) {
return match.charAt(match.length-1).toUpperCase();
}); // HelloWorld
Run Code Online (Sandbox Code Playgroud)
这是一个工作的班轮:
const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));
Run Code Online (Sandbox Code Playgroud)
它根据RegExp中提供的字符列表分割小写字符串[.\-_\s](在[]!中添加更多),并返回一个word数组。然后,它将字符串数组简化为一个带有大写首字母的串联单词字符串。因为reduce没有初始值,所以它将以第二个单词开头的大写字母开头。
如果需要PascalCase,只需将一个初始的空字符串添加,'')到reduce方法中即可。
因为这个问题需要另一个答案......
我尝试了以前的几种解决方案,但它们都有一个或另一个缺陷。有些没有删除标点符号;有些没有处理数字的情况;有些没有连续处理多个标点符号。
他们都没有处理像a1 2b. 这种情况没有明确定义的约定,但其他一些stackoverflow 问题建议用下划线分隔数字。
我怀疑这是性能最高的答案(三个正则表达式通过字符串,而不是一两个),但它通过了我能想到的所有测试。不过,老实说,我真的无法想象您进行了如此多的驼峰式转换以至于性能很重要的情况。
(我将其添加为npm 包。它还包含一个可选的布尔参数,用于返回 Pascal Case 而不是 Camel Case。)
const underscoreRegex = /(?:[^\w\s]|_)+/g,
sandwichNumberRegex = /(\d)\s+(?=\d)/g,
camelCaseRegex = /(?:^\s*\w|\b\w|\W+)/g;
String.prototype.toCamelCase = function() {
if (/^\s*_[\s_]*$/g.test(this)) {
return '_';
}
return this.replace(underscoreRegex, ' ')
.replace(sandwichNumberRegex, '$1_')
.replace(camelCaseRegex, function(match, index) {
if (/^\W+$/.test(match)) {
return '';
}
return index == 0 ? match.trimLeft().toLowerCase() : match.toUpperCase();
});
}
Run Code Online (Sandbox Code Playgroud)
测试用例(Jest)
test('Basic strings', () => {
expect(''.toCamelCase()).toBe('');
expect('A B C'.toCamelCase()).toBe('aBC');
expect('aB c'.toCamelCase()).toBe('aBC');
expect('abc def'.toCamelCase()).toBe('abcDef');
expect('abc__ _ _def'.toCamelCase()).toBe('abcDef');
expect('abc__ _ d_ e _ _fg'.toCamelCase()).toBe('abcDEFg');
});
test('Basic strings with punctuation', () => {
expect(`a'b--d -- f.h`.toCamelCase()).toBe('aBDFH');
expect(`...a...def`.toCamelCase()).toBe('aDef');
});
test('Strings with numbers', () => {
expect('12 3 4 5'.toCamelCase()).toBe('12_3_4_5');
expect('12 3 abc'.toCamelCase()).toBe('12_3Abc');
expect('ab2c'.toCamelCase()).toBe('ab2c');
expect('1abc'.toCamelCase()).toBe('1abc');
expect('1Abc'.toCamelCase()).toBe('1Abc');
expect('abc 2def'.toCamelCase()).toBe('abc2def');
expect('abc-2def'.toCamelCase()).toBe('abc2def');
expect('abc_2def'.toCamelCase()).toBe('abc2def');
expect('abc1_2def'.toCamelCase()).toBe('abc1_2def');
expect('abc1 2def'.toCamelCase()).toBe('abc1_2def');
expect('abc1 2 3def'.toCamelCase()).toBe('abc1_2_3def');
});
test('Oddball cases', () => {
expect('_'.toCamelCase()).toBe('_');
expect('__'.toCamelCase()).toBe('_');
expect('_ _'.toCamelCase()).toBe('_');
expect('\t_ _\n'.toCamelCase()).toBe('_');
expect('_a_'.toCamelCase()).toBe('a');
expect('\''.toCamelCase()).toBe('');
expect(`\tab\tcd`.toCamelCase()).toBe('abCd');
expect(`
ab\tcd\r
-_
|'ef`.toCamelCase()).toBe(`abCdEf`);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
238761 次 |
| 最近记录: |