Javascript / jQuery:分割camelcasestring并添加连字符而不是空格
我会想象这是一个正则expression式的多个部分的情况,但是如何将大写字母的驼峰string转换为小写字母,然后在每个新string之间添加一个连字符?
例如:
thisString
会成为:
这串
尝试像这样:
var myStr = 'thisString'; myStr = myStr.replace(/([az])([AZ])/g, '$1-$2').toLowerCase();
迟到了,但是这个解决scheme适用于单个字母是骆驼的情况。
'thisIsATest'.replace(/([a-zA-Z])(?=[AZ])/g, '$1-').toLowerCase(); // this-is-a-test
尝试以下操作:
var token = document.getElementsByTagName('strong')[0].innerHTML, replaced = token.replace(/[az][AZ]/g, function(str, offset) { return str[0] + '-' + str[1].toLowerCase(); }); alert(replaced);
示例 – http://jsfiddle.net/7DV6A/2/
stringreplace
function的文档:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
String.prototype.camelCaseToDashed = function(){ return this.replace(/([az])([AZ])/g, '$1-$2').toLowerCase(); } // Usage "SomeVariable".camelCaseToDashed();
我不知道为什么所有这些解决scheme都如此复杂,但我只是发现这足够了:
function camelCaseToDash(input){ // replace Capital letter with the letter + a dash: '-', then lowercase everything. return input.replace(/([AZ])/g, '-$1').toLowerCase(); } //or, using a callback function, directly lowercasing. function camelCaseToDashCallback(input){ //replace capital letter with lowercase variant + a dash '-'. return input.replace(/([AZ])/g, (x)=> "-"+ x.toLowerCase()); }
通常选项1更快,但: https : //jsfiddle.net/4557z/17/