如何在JavaScript中将字符串中每个单词的第一个字母大写,并将所有空格更改为下划线

How to capitalize first letter of each word in a string and change all spaces to underscores in JavaScript

本文关键字:下划线 空格 字符串 JavaScript 第一个 单词      更新时间:2023-09-26

我正在尝试用JavaScript实现一个函数,该函数为给定的输入值提供这样的输出

输入:stack overflow

输出:Stack_Overflow

输入:the big bang theory

输出:The_Big_Bang_Theory

我已经编写了将字母大写的代码,但似乎不知道如何同时调用同一输入上的两个函数。我对Javascript还比较陌生,如果有任何帮助,我将不胜感激。我将在这里分享我的代码以进一步澄清

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<body>
<input id="myInput" type="text" value="" size="50" />
<pre id="myOutput" type="myInput">type something in the box above</pre>
<script>
String.prototype.capitalize = function(){
return this.toLowerCase().replace( /'b'w/g, function (m) {
return m.toUpperCase();
});
};
String.prototype.replaceAll = function(){
if(!search || !replace){return this;}
return this.replace(/ /g,"_"), function (n){
return n;
});
};
var myInput = document.getElementById('myInput');
var myOutput = document.getElementById('myOutput')
myInput.addEventListener('input', function(e) {
myOutput.innerHTML = this.value.capitalize();

});
myInput.addEventListener('input', function(f)) {
myOutput.innerHTML = this.value.replaceAll();
});
</script>
</body>
</html>

您实际上并没有向capitalize函数传递任何参数。为了适应这一点,我对您的代码进行了轻微的编辑。

// first check to see if `capitalize` doesn't
// already exist on the prototype - don't go overwriting
// native methods :)
if (!('capitalize' in String.prototype)) {
  String.prototype.capitalize = function() {
    return this.toLowerCase().replace(/'b'w/g, function(m) {
      return m.toUpperCase();
    });
  };
}
if (!('replaceAll' in String.prototype)) {
  // pass in search and replace as arguments
  String.prototype.replaceAll = function(search, replace) {
    if (!search || !replace) return this;
    // then just do a replace using the arguments
    return this.replace(search, replace, 'g');
  };
}
var str = 'the big bang theory';
str.capitalize().replaceAll(' ', '_'); // The_Big_Bang_Theory

演示

试试这个

var str = 'stack overflow';
str = str.toLowerCase().replace(/'b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
str= str.replace(' ','_');
alert(str);

https://jsfiddle.net/n6nqpwe6/

更新

我已经在String类中嵌入了该方法(如您所做的那样称为capitalize),并将代码放入正在运行的演示中:

String.prototype.capitalize = function() {
  return this.toLowerCase().replace(
     /'b('w)('w*)( *)/g, 
     function(all, f, r, s) { return f.toUpperCase() + (r?r:'') + (s?'_':''); }
  );
};
 
var tests = ['stAck oVerFlow','the bIg bANg theory'];
while(t = tests.pop()){ 
    console.log(t, ' -> ', t.capitalize());
}
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Legenda

正则表达式使用捕获组进行匹配:

  • 'b('w):正则表达式单词的第一个字符(相当于[a-zA-Z0-9_])。我不使用[a-z]来匹配已经以大写字母或数字(或下划线,是否要避免这种情况?)开头的单词后面的空格
  • ('w*):正则表达式单词的其余部分
  • ( *):一个或多个空间

然后在闭包中,它将第一个字母大写,附加单词的其余部分(如果存在),如果单词后面实际上有一个或多个空格,则附加下划线"_"。