Javascript/jQuery:拆分驼峰字符串并添加连字符而不是空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8955533/
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
Javascript/jQuery: Split camelcase string and add hyphen rather than space
提问by user1048007
I would imagine this is a multiple part situation with regex, but how would you split a camelcase string at the capital letters turning them in to lowercase letters, and then adding a hyphen between each new string?
我想这是一个正则表达式的多部分情况,但是你如何在大写字母处拆分驼峰字符串,将它们变成小写字母,然后在每个新字符串之间添加一个连字符?
For example:
例如:
thisString
这个字符串
would become:
会成为:
this-string
这个字符串
回答by Wouter J
Try something like:
尝试类似:
var myStr = 'thisString';
myStr = myStr.replace(/([a-z])([A-Z])/g, '-').toLowerCase();
回答by Syon
Late to answer, but this solution will work for cases where a single letter is camel cased.
回答晚了,但此解决方案适用于单个字母为驼峰式大小写的情况。
'thisIsATest'.replace(/([a-zA-Z])(?=[A-Z])/g, '-').toLowerCase(); // this-is-a-test
回答by xandercoded
Try the following:
请尝试以下操作:
var token = document.getElementsByTagName('strong')[0].innerHTML,
replaced = token.replace(/[a-z][A-Z]/g, function(str, offset) {
return str[0] + '-' + str[1].toLowerCase();
});
alert(replaced);
Example - http://jsfiddle.net/7DV6A/2/
示例 - http://jsfiddle.net/7DV6A/2/
Documentation for the string replace
function:
字符串replace
函数的文档:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
回答by Bilal Iqbal
String.prototype.camelCaseToDashed = function(){
return this.replace(/([a-z])([A-Z])/g, '-').toLowerCase();
}
// Usage
"SomeVariable".camelCaseToDashed();
回答by Joel Harkes
I don't know why all these solutions are so complex but i simply found this to be enough:
我不知道为什么所有这些解决方案都如此复杂,但我发现这已经足够了:
function camelCaseToDash(input){
// replace Capital letter with the letter + a dash: '-', then lowercase everything.
return input.replace(/([A-Z])/g, '-').toLowerCase();
}
//or, using a callback function, directly lowercasing.
function camelCaseToDashCallback(input){
//replace capital letter with lowercase variant + a dash '-'.
return input.replace(/([A-Z])/g, (x)=> "-"+ x.toLowerCase());
}
generally option 1 is faster though: https://jsfiddle.net/4557z/17/
通常,选项 1 更快:https: //jsfiddle.net/4557z/17/