Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: string Manipulation [duplicate]

I am having a hard time chaining some methods together. Can you please provide some assistance?

The end result should = Mickey MOUSE

var name = "MicKEy MOUse";

function nameChanger(oldName) {
    var finalName = oldName;

    var splitString = name.split(' ');

    var fname = splitString.slice(0,1);
    var fname_lower = fname.toLowerCase.slice(1,6);


    return fname_lower;

};
console.log(nameChanger(name));

Since I am trying to learn the methods in the function I would appreciate assistance on those items. However, if there are more eloquent ways of performing the same action I would appreciate that input as well.

Thank you in advance for your knowledge and direction.

like image 312
user2654953 Avatar asked Apr 14 '26 15:04

user2654953


1 Answers

  1. Split the name into two, based on the space character

    var splitString = oldName.split(' ');
    
  2. Convert the entire first string to lowercase and the second string to uppercase.

    var fname = splitString[0].toLowerCase();
    var lname = splitString[1].toUpperCase();
    
  3. Now, just create a new String from fname, by changing the first character to upper case, join it with lname and return it, like this

    return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
    

So, your complete function would look like this

function nameChanger(oldName) {
    var splitString = oldName.split(' ');
    var fname = splitString[0].toLowerCase();
    var lname = splitString[1].toUpperCase();
    return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
};

Note: You might be wondering, why we are doing this

fname[0].toUpperCase() + fname.substring(1)

to change just the first character of fname. In JavaScript, Strings are immutable objects. Once a String object is created, it can never be changed. So, we are creating a new String object, based on the modified first character of fname and the rest of fname.

like image 85
thefourtheye Avatar answered Apr 17 '26 04:04

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!