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

输入:stack overflow

输出:Stack_Overflow

输入:the big bang theory

输出:The_Big_Bang_Theory

我已经编写了将字母大写的代码,但似乎无法弄清楚如何在同一输入上同时调用这两个函数。我是Java的新手,任何帮助将不胜感激。我将在此处分享我的代码以进一步阐明

<!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


DEMO

09-18 05:27