如何用两个大写字母正确"核心下"



在javascript中,我有这个简单的字符串:justAQuestion我想把它变换成just_a_question。使用下划线。字符串,灰烬。字符串我有相同的坏结果:just_aquestion .

你知道怎么解决这个问题吗?

下面是重现这个问题的JSBin: http://emberjs.jsbin.com/tudepeceli/edit?html,js,output

这是因为AQ被视为单个'单词'。如果您总是想用下划线及其小写版本替换大写字母,请使用如下内容:

var replacement = source.replace(/[A-Z]/g, function(m) {
  return '_' + m.toLowerCase();
});

…或者只是……

source.replace(/([A-Z])/g, '_$1').toLowerCase();

当您必须对以大写字母开头的字符串进行破折号分隔时,它会变得有点棘手。一种可能的情况是将所有前缀'_'替换为…

source.replace(/^_+/, '');

你可以这样做:

var s = "justAQuestion";
var n = s.replace(/([A-Z])/g, "_$1").toLowerCase();

产率:just_a_question

上面的代码假设没有ThisIsJustAQuestion这样的单词(即开头是大写的)。

function transferString(str){
  
  newStr = "";
  for(i = 0; i < str.length; i++){
     if(str[i] == str[i].toUpperCase()){
       newStr += "_" +  str[i].toLowerCase() + "_";
     }else{
       newStr += str[i];
    }
  }
  return newStr;
}
alert(transferString("justAQuestion"));

你可以创建自己的方法,下面是工作代码。

String.prototype.allUnderscore=function(str){
  return this.replace(/([A-Z])/g, '_$1').toLowerCase();
}

最新更新