如何将字符串中每个单词的首字母大写,并将所有空格更改为JavaScript

时间:2015-12-17 10:52:37

标签: javascript html regex

我正在尝试在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>

2 个答案:

答案 0 :(得分:0)

试试这个

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/

答案 1 :(得分:0)

<强>更新

我已经在String类中嵌入了这个方法(就像你做的那样称为capitalize)并将代码放在一个正在运行的demo中:

&#13;
&#13;
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());
}
&#13;
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
&#13;
&#13;
&#13;

<强>勒亘

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

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

然后在封闭中,它将第一个字母大写,将其余部分(如果有的话)附加到下面并附加一个下划线&#39; _&#39;如果在单词后面实际有一个或多个空格。