如何用两个大写字母正确“下划线”

时间:2015-10-08 11:14:18

标签: javascript regex string

在javascript中,我有这个简单的字符串:justAQuestion 我想将其转换为just_a_question。 使用Fcntlunderscore.string我有同样糟糕的结果: just_aquestion

知道如何解决这个问题吗?

这是一个重现问题的JSBin:Ember.String

4 个答案:

答案 0 :(得分:2)

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

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

......或者只是......

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

当你必须用大写字母开头来划分字符串时,它会变得有点棘手。一种可能的情况就是替换所有前缀' _'与...

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

答案 1 :(得分:1)

你可以这样做:

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

收益率:just_a_question

以上假设您没有ThisIsJustAQuestion之类的单词(即开头的大写字母)。

答案 2 :(得分:0)



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"));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以创建自己的方法,Here是工作代码。

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