gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:33:32 26 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中实现一个函数,该函数为给定的输入值提供如下所示的输出

输入:堆栈溢出

输出:Stack_Overflow

输入:大爆炸理论

输出: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

DEMO

关于javascript - 如何在 JavaScript 中将字符串中每个单词的第一个字母大写并将所有空格更改为下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34332766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com