Javascript 将破折号分隔的字符串转换为驼峰式大小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10425287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:15:00  来源:igfitidea点击:

Convert dash-separated string to camelCase?

javascriptregex

提问by Hoa

For example suppose I always have a string that is delimited by "-". Is there a way to transform

例如,假设我总是有一个由“-”分隔的字符串。有没有办法改造

it-is-a-great-day-today

今天是个好日子

to

itIsAGreatDayToday

今天是个好日子

Using RegEx?

使用正则表达式?

回答by apsillers

Yes (editedto support non-lowercase input and Unicode):

(已编辑以支持非小写输入和 Unicode)

function camelCase(input) { 
    return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
        return group1.toUpperCase();
    });
}

See more about "replace callbacks" on MDN's "Specifying a function as a parameter"documentation.

在 MDN 的“将函数指定为参数”文档中查看有关“替换回调”的更多信息。

The first argument to the callback function is the full match, and subsequent arguments are the parenthesized groups in the regex (in this case, the character after the the hyphen).

回调函数的第一个参数是完全匹配,后续参数是正则表达式中括号中的组(在这种情况下,连字符之后的字符)。

回答by maerics

You can match on the word character after each dash (-) or the start of the string, or you could simplify by matching the word character after each word boundary (\b):

您可以匹配每个破折号 ( -) 或字符串开头之后的单词字符,或者您可以通过匹配每个单词边界 ( \b)之后的单词字符来简化:

function camelCase(s) {
  return (s||'').toLowerCase().replace(/(\b|-)\w/g, function(m) {
    return m.toUpperCase().replace(/-/,'');
  });
}
camelCase('foo-bar'); // => 'FooBar'
camelCase('FOo-BaR-gAH'); // => 'FooBarGah'

回答by Joseph

Here's a demo

这是一个演示

var test = 'It-is-a-great-day-today';

function camelize(str) {
    return str[0].toLowerCase() + str.replace(/-([a-z])/g, function(a, b) {
        return b.toUpperCase();
    }).slice(1);
}

console.log(camelize(test));

回答by anubhava

This should also work:

这也应该有效:

function camelCase(str) {
  return str.replace(/^.|-./g, function(letter, index) {
    return index == 0 ? letter.toLowerCase() : letter.substr(1).toUpperCase();
  });
}

And IMHO it is little bit more efficient since we're not converting whole input string to lowercase first and then convert to uppercase if needed. This function only converts first letter to lowercase and then every character after hyphen -to uppercase.

恕我直言,它的效率更高一些,因为我们不会先将整个输入字符串转换为小写,然后根据需要转换为大写。此函数仅将第一个字母转换为小写,然后将连字符后的每个字符转换-为大写。

回答by Lior Erez

Another method using reduce:

另一种使用reduce 的方法:

function camelCase(str) {
  return str
    .split('-')
    .reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
}

回答by codeBelt

This works great but someone might be able to clean it up.

这很好用,但有人可能会清理它。

var toCamelCase = function(str) {
        // Replace special characters with a space
        str = str.replace(/[^a-zA-Z0-9 ]/g, " ");
        // put a space before an uppercase letter
        str = str.replace(/([a-z](?=[A-Z]))/g, ' ');
        // Lower case first character and some other stuff that I don't understand
        str = str.replace(/([^a-zA-Z0-9 ])|^[0-9]+/g, '').trim().toLowerCase();
        // uppercase characters preceded by a space or number
        str = str.replace(/([ 0-9]+)([a-zA-Z])/g, function(a,b,c) {
            return b.trim() + c.toUpperCase();
        });
        return str;
};

console.log(toCamelCase('hyphen~name~ format'));
console.log(toCamelCase('hyphen.name.format'));
console.log(toCamelCase('hyphen-name-format'));
console.log(toCamelCase('Hyphen-Dame-Gormat'));
console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase(' e    Equipment Class Name'));
console.log(toCamelCase('under9score_name_format'));
console.log(toCamelCase('Enderscore_name_format'));
console.log(toCamelCase('EnderscoreBameFormat'));
console.log(toCamelCase('_EnderscoreBameFormat'));

http://jsbin.com/yageqi/1/edit?js,console

http://jsbin.com/yageqi/1/edit?js,console

回答by Joon

I know this question is a bit old but,

我知道这个问题有点老了,但是,

Here's my version of camelCase function:

这是我的camelCase函数版本:

var camelCase = (function () {
    var DEFAULT_REGEX = /[-_]+(.)?/g;

    function toUpper(match, group1) {
        return group1 ? group1.toUpperCase() : '';
    }
    return function (str, delimiters) {
        return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
    };
})();

It handles all of the following edge cases:

它处理以下所有边缘情况:

  • takes care of both underscores and hyphens by default (configurable with second parameter)
  • string with unicode characters
  • string that ends with hyphens or underscore
  • string that has consecutive hyphens or underscores
  • 默认情况下同时处理下划线和连字符(可使用第二个参数配置)
  • 带有 unicode 字符的字符串
  • 以连字符或下划线结尾的字符串
  • 具有连续连字符或下划线的字符串

Here's a link to live tests: http://jsfiddle.net/avKzf/2/

这是现场测试的链接:http: //jsfiddle.net/avKzf/2/

Here are results from tests:

以下是测试结果:

  • input: "ab-cd-ef", result: "abCdEf"
  • input: "ab-cd-ef-", result: "abCdEf"
  • input: "ab-cd-ef--", result: "abCdEf"
  • input: "ab-cd--ef--", result: "abCdEf"
  • input: "--ab-cd--ef--", result: "AbCdEf"
  • input: "--ab-cd-__-ef--", result: "AbCdEf"
  • 输入:“ab-cd-ef”,结果:“abCdEf”
  • 输入:“ab-cd-ef-”,结果:“abCdEf”
  • 输入:“ab-cd-ef--”,结果:“abCdEf”
  • 输入:“ab-cd--ef--”,结果:“abCdEf”
  • 输入:“--ab-cd--ef--”,结果:“AbCdEf”
  • 输入:“--ab-cd-__-ef--”,结果:“AbCdEf”

Notice that strings that start with delimiters will result in a uppercase letter at the beginning. If that is not what you would expect, you can always use lcfirst. Here's my lcfirst if you need it:

请注意,以分隔符开头的字符串将导致以大写字母开头。如果这不是您所期望的,您可以随时使用 lcfirst。如果您需要,这是我的 lcfirst:

function lcfirst(str) {
    return str && str.charAt(0).toLowerCase() + str.substring(1);
}

回答by Gabriel Santos

See http://jsfiddle.net/54ZcM/

http://jsfiddle.net/54ZcM/

function camelCase(string) {
    return string.toLowerCase().replace(/(\-[a-zA-Z])/g, function() {
        return .toUpperCase().replace('-','');
    })
}

alert(camelCase('fOo-BarBA-fo'));

回答by SoEzPz

var string = "it-is-a-great-day-today";
or
var string = "it_is_a_great_day_today";

var regex = /(_|-)([a-z])/g;

string.toLowerCase().replace(regex, toCamelCase );

function toCamelCase( string ){
  return string[1].toUpperCase();
}

Output: "itIsAGreatDayToday";

回答by Chetan Ankola

here is the jsfiddle you can play with to test this http://jsfiddle.net/5n84w/2/

这是您可以用来测试此http://jsfiddle.net/5n84w/2/的 jsfiddle

```

``

/**
 * Function to convert any string to camelCase
 * var regex = 'chetan-Ankola###.com---m13ok#-#alo(*finding!R%S#%-GFF'; 
 * Where [-_ .] is the seperator, you can add eg: '@' too
 * + is to handle repetition of seperator           
 * ? is to take care of preceeding token 
 * match nov(ember)? matches nov and november
 */
var camelCaser = function (str) {
    var camelCased = str.replace(/[-_ .]+(.)?/g, function (match, p) {
        if (p) {
            return p.toUpperCase();
        }
        return '';
    }).replace(/[^\w]/gi, '');
    return camelCased;
};

```

``