Richy
Richy

Reputation: 167

Capitalize first letter and remove space in string

Got some code to capitalize the first letter of every word in a string. Can someone please help me update it so it also removes all spaces within the string once the first letters are Capped.

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

Upvotes: 0

Views: 9407

Answers (5)

mhelcabs
mhelcabs

Reputation: 1

function wordSearch()
{
   var paragraph=document.getElementById("words").value;
   let para2=paragraph.replace(/\s+/g,'');//remove whitespaces
   let para3=para2.charAt(0).toUpperCase()+para2.slice(1); 
   //uppercase first letter
   alert(para3);
 }

Upvotes: 0

JayChase
JayChase

Reputation: 11525

As an alternative you can split the string on the space, capitalize each word and then join them back together again:

"pascal case".split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1) ).join('')

Upvotes: 2

jcubic
jcubic

Reputation: 66650

Try this:

var input = 'lorem ipsum dolor sit amet';
// \w+ mean at least of one character that build word so it match every
// word and function will be executed for every match
var output = input.replace(/\w+/g, function(txt) {
  // uppercase first letter and add rest unchanged
  return txt.charAt(0).toUpperCase() + txt.substr(1);
}).replace(/\s/g, '');// remove any spaces

document.getElementById('output').innerHTML = output;
<div id="output"></div>

You can also use one regex and one replace:

var input = 'lorem ipsum dolor sit amet';
// (\w+)(?:\s+|$) mean at least of one character that build word
// followed by any number of spaces `\s+` or end of the string `$`
// capture the word as group and spaces will not create group `?:`
var output = input.replace(/(\w+)(?:\s+|$)/g, function(_, word) {
  // uppercase first letter and add rest unchanged
  return word.charAt(0).toUpperCase() + word.substr(1);
});

document.getElementById('output').innerHTML = output;
<div id="output"></div>

Upvotes: 8

Pawan Prajapati
Pawan Prajapati

Reputation: 1

Page has a nice example of how to capitalize each word in a string in JavaScript: http://alvinalexander.com/javascript/how-to-capitalize-each-word-javascript-string

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167220

You can use a simple helper function like:

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

Upvotes: 1

Related Questions