Open Laboratory for Technocrats

Grab the developer role, learn concepts & prepare with senior software engineers to get solutions for problems in a software job. Coding and Programming Solutions crafted for you.

PHP’s UCWords & UCFirst Functions In JavaScript

UCWords & UCFirst Functions In PHP Replication in JS

JavaScript is also having various functionalities regarding string manipulation, But the PHP developers who are working new to it faces a lot of need of the same functionality as they do it in PHP functions.

Today lets discuss the two very common functions ucfirst function in php and ucwords function in php that every developer who are using PHP uses.

ucwords() :

Returns a string with the first character of each word in string capitalized, if that character is alphabetic.

Now let's see how we can implement this same functionality in core javascript, without using any framework.

String.prototype.jsUCWords = function () {
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
        })
    }
Example and Usage:

var stringVariable = "This is my first js test";
stringVariable.jsUCWords();
 // Output: This Is My First Js Test


Similarly now lets have a look into next function called ucfirst():

Returns a string with the first character of str capitalized, if that character is alphabetic. 
Now lets see how we can implement this same functionality in core javascript,without using any framework.
String.prototype.jsUCFirst = function () {    
    return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase()  
}
 Example and Usage:

var stringVariable = "this is my first js test";
stringVariable.jsUCFirst();
 // Output: This is my first js test

These are two very common and easy to use function in PHP which we have implemented using plain javascript.

Happy Coding :)


Top #3 Articles

Most Read