Sue-May Xu
Sue-May Xu

Reputation: 500

Why doesn't my capitalization function run as expected?

Not sure what is wrong with my code. I want to capitalize each word from input field and display it in "showcase".

Below is my code:

Convert

<script>
function convert(sst) {
    return sst.charAt(0).toUpperCase() + sst.slice(1);
    document.getElementById("showcase").innerHTML = n;
}
</script>

Upvotes: 1

Views: 63

Answers (3)

Ele
Ele

Reputation: 33726

  • You have a return before document.getElementById("showcase").innerHTML = n;

  • You didn't declare the variable n.

Look at this code snippet with those fixes:

function convert(sst) {
    return sst.charAt(0).toUpperCase() + sst.slice(1);        
}

// To reuse your function 'convert', just return the converted value.
document.getElementById("showcase").innerHTML = convert("ele");
<p id="showcase">
</p>
See? now it's working your logic.

Important: Your approach works for one word only :-)

UPDATE

This is your approach to capitalized all words

document.getElementById('myButton').addEventListener('click', function() {
  document.getElementById("showcase").innerHTML = convert(document.getElementById('inputfield').value);
});

function convert(str) {
  return str.replace(/\w\S*/g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
  });
}
<body> <input type="text" id="inputfield" /> <button id='myButton'>Convert</button>
  <div id="showcase"></div>
</body>

Upvotes: 2

Endless
Endless

Reputation: 37815

This will capitalize each word unlike the other answers One other different is that it will lowercase the other letters that follows (like sTRING in this example) similar to the others this also return a value from the function so you can re-use the function, this is also called a pure function doing just one thing.

function capitalizeWords(str) {
  return str.replace(/\w\S*/g, function (txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
}

var str = capitalizeWords('js sTRING exercises');
document.getElementById("showcase").innerText = str;
<p id="showcase"></p>

Also notice that i switched from innerHTML to innerText for better safety. Any dangerous html code could sneak in if using innerHTML

Upvotes: 1

Javier Gonzalez
Javier Gonzalez

Reputation: 1015

It is better to return a value from the convert function so you can re-use the function:

<script>
    function convert(sst) {
        return sst.charAt(0).toUpperCase() + sst.slice(1);
    }
    var n = convert('hello');
    document.getElementById("showcase").innerHTML = n;
    var m = convert('world');
    document.getElementById("otherElement").innerHTML = m;
</script>

Upvotes: 1

Related Questions