Wednesday 27 December 2017

Capitalizing first letter and replaceAt particular index of String in Javascript

These are the two functions that will help in most cases where we need to replace index of a particular stiring.

Capitalizing first letter of a string can also be done using css property text-transform:capitalize, in many cases such as if we want to show a stirng with first letter capital in title attribute on hover this does'nt work. So this is handy javascript function that will be useful.


//replaceAt index of particluar string

 
function replaceAt(str, index, replacement) {
    return str.substr(0, index) + replacement + str.substr(index + replacement.length);
}


//capitalize first letter of a string

function capitalizeFirstLetter(string) {

    if(typeof string != "undefined" && string != "" && string != "undefined"){

    return string.charAt(0).toUpperCase() + string.slice(1);

    } else {

            return string;

    }

}

No comments:

Post a Comment