Posts

Showing posts from May, 2017

Javascript: Capitalize First Word of String (EASY)

In Javascript, you can make the first word uppercase by using the technique below. function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } var str = "lorem ipsum dolor"; capitalize(str); // output: "Lorem ipsum dolor" To explain what's going on, the function takes the first letter of given string and convert it to uppercase then append to the rest of the given string. We can modify the String.prototype if you don't mind a little setback on the performance. String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); } Now we can call the function in object oriented way: var str = "lorem ipsum dolor"; console.log(str.capitalize()); // output: "Lorem ipsum dolor"

Javascript: Get Query String (Easy)

Image
This tutorial assumes that you already know what a query string is. If you are looking for a way to get the query string values and assign to a variable, then check the following block of codes. Do note that this is only pure Javascript. No need for plugins or libraries. var queryString = {}; var params = location.search.substr(1).split('&'); params.forEach(function( param ){     [name, value] = param.split('=');     queryString[name] = decodeURIComponent((value).replace(/\+/g, '%20')); }); // check the output console.log(queryString); In the above code, we use location.search which is the way to get the query string. The result of location.search . would be a string type like this: ?key1=value1&key2=value2 To get the desired result we want, we first remove the '?' mark with .substr(1) , then split the string with delimiter '&' The resulting array is then looped through using .forEach() . For each array item we then spli