Design Development JavaScript

JavaScript 101-#8 – Strings

Plan for today is quite simple … We will continue in JavaScript 101 series. Last time talked finished deep dive into numbers and the next topic, we will cover today are strings. Because we already covered the basics in post about data types, we will jump right into methods and properties you can use with strings and practicing on examples. If you missed the intro part on data types and you might read that first. Let’s dive in.

All properties and methods can be used in two ways … Write the string (inside the quotes) followed by dot and the name of property or method. Another way is to store the string inside variable and then use the name of variable, again, followed by dot and the name of property or method.

Length

Very often used string property is length. This property returns an integer, which is length of the whole string. Space between words or characters inside string are also counted. When you try to use length property directly with number, you will get an error. In case of number in variable, the result will be „undefined“. Programmers often use length property in conditionals and loops, which will be covered in future post.

JavaScript:

console.log(„JavaScript“.length); // result – 10
console.log(„New York“); // result – 8
var exampleStr = „Dogma“;
console.log(exampleStr.length); // result – 5
var number = 5;
console.log(number.length); // result – undefined
console.log(6532.length); // result – error

toLowerCase() and toUpperCase()

First two string methods we will take a look at are toLowerCase() and toUpperCase(). Job these methods do is quite simple … They will convert all characters of the string to lowercase or uppercase letters. These methods have alternatives – toLocaleLowerCase() and toLocaleUpperCase() which converts the string into upper or lower case according to host’s locale.

JavaScript:

console.log(„ruby“.toUpperCase()); // result – “RUBY”
console.log(„San Diego“.toLowerCase()); // result – “san diego”
var city = “Prague”;
console.log(city.toUpperCase()); // result - “PRAGUE”
console.log(city.toLowerCase()); // result - “prague”

slice()

When you use this method on some string, it will return piece of it. Unlike previous methods, slice() takes two parameters. Both parameters are integers. First is for position (index) to start and second for position (index) to end. Same as with arrays, indexes in strings too starts with zero, so if you want to start with the first character, use zero as the first parameter. Second parameter is optional and if you omit it, JavaScript will return string from index you used for start till the end of string. Important thing about the second argument … JavaScript will not include the character on that index in result, character on starting position will be. If you use negative number as a parameter, it will cause counting from end instead of start of the string.

JavaScript:

var string = “Good job!”;
console.log(string.slice(0)); // result - “Good job!”
console.log(“programming”.slice(0, 4)); // result - “prog”
console.log(“programming”.slice(3)); // result - “gramming”
console.log(“programming”.slice(-1)); // result - “g”
console.log(“programming”.slice(-3, -1)); // result - “in”
console.log(“programming in JavaScript”.slice(-13, -5)); // result - “in JavaS”

split()

Next method is to try is split. This method will cut the string into pieces and return an array according to parameter you use. split() takes one parameter that is a character or regular expression and will be used as separator and optional parameter for limiting the items in result array. So, if you set the limit to 5, array will contain only first five items according to separator. If you don’t use any parameter, array will contain the whole string as single item. Important note … Character used as separator is not included in array. Also, pay attention to lowercase and uppercase letters.

JavaScript:

console.log(“Writing in JavaScript.”.split()); // result - [“Writing in JavaScript.“]
console.log(“Writing in JavaScript.”.split(“ ”)); // result - [“Writing”, ”in”, ”JavaScript.”]
console.log(“Writing in JavaScript.”.split(“ ”, 1)); // result - [“Writing”]
console.log(“Writing in JavaScript.”.split(“i”, 3)); // result - [“Wr”, “tt”, “ng “]
console.log(“Writing in JavaScript.”.split(“i”)); // result - [“Wr”, “tt”, “ng “, “n JavaScr”, “pt.”]
console.log(“Writing in JavaScript.”.split(“Java”)); // result - [“Writing”, ”in”, ”Script.”]
console.log(“Writing in JavaScript.”.split(“JAVA”)); // result - [“Writing”, ”in”, ”JavaScript.”]

substr()

substr() method work in similar fashion like slice(). It also takes two arguments, first for starting position (index), but the second is different. Second argument specifies how many characters you want to return. If you omit the second argument, you will get string from the starting position to the end. Character on starting position is included in result string. Negative number as a first parameter (starting position) will cause counting from the end of the string.

JavaScript:

console.log(“Australia”.substr(0)); // result - “Australia”
console.log(“Australia”.substr(3)); // result - “tralia”
console.log(“Australia”.substr(4, 2)); // result - “ra”
var exx = “Hokkaido, Honshu, Shikoku, Kyushu”;
console.log(exx.substr(0, 15)); // result - “Hokkaido, Honsh”
console.log(exx.substr()); // result - “Hokkaido, Honshu, Shikoku, Kyushu”
console.log(exx.substr(13, 7)); // result - “shu, Sh”
console.log(exx.substr(-5, 2)); // result - “yu”
console.log(exx.substr(-12, 6)); // result - “koku, ”

charAt() and charCodeAt()

These two methods work in similar style. They both takes one parameter – index marking the position of character you want to get. The difference is that the charCodeAt() method returns a Unicode of character instead of the character.

JavaScript:

var sentence = “work and fun”;
console.log(sentence.charAt(10)); // result - “u”
console.log(sentence.charAt(0)); // result - “w”
console.log(sentence.charCodeAt(12)); // result - 117
console.log(sentence.charCodeAt(0)); // result – 119

indexOf() and lastIndexOf()

Unlike the previous pair of methods, this pair takes two parameters – first for string (character, word, sentence …) you are looking for and second, optional, for starting position (index). When used, they will return the index of FIRST occurrence of searched parameter. If you want to skip the first occurrence, just set the starting position after it. The difference between these two is that lastIndexOf() in reverse direction – from end to start. In case of searching for words or phrases, you will get position of the first character.

JavaScript:

console.log(“Clarity on sight.”.indexOf(“i”)); // result – 4
console.log(“Clarity on sight.”.indexOf(“i”, 5)); // result – 12 (second “i”)
console.log(“Clarity on sight.”.indexOf(“on”)); // result – 8 (index of “o”)
console.log(“Clarity on sight.”.lastIndexOf (“i”)); // result – 12
console.log(“Clarity on sight.”.lastIndexOf (“i”, 11)); // result – 4 (first “i”)

search()

This method takes one parameter – searched string and will return index of its first occurrence.

JavaScript:

console.log(“Understaning is important.”.search(“n”)); // result – 1
console.log(“Understaning is important.”.search(“ is ”)); // result – 12
console.log(“Understaning is important.”.search(“Understaning”)); // result – 0

replace()

replace() takes two parameters – value for replacement and new value. It will change only first occurrence of searched value. This method is case sensitive.

JavaScript:

console.log(“Skip and skim.”.replace(“i”, “a”)); // result – “Skap and skim.”
console.log(“Skip and skim.”.replace(“and”, “or”)); // result – “Skip or skim.”

trim()

trim() method takes no parameter and returns string without white space on sides. It will remove ONLY white space on beginning or end of the string.

JavaScript:

console.log(“White space.”.trim()); // result – “White space.”
console.log(“ White space. ”.trim()); // result – “White space.”

concat()

Last method we will talk about is concat(). This method will join two or more strings according to specified parameters.

JavaScript:

var start= “Open ”;
var end = “source”;
console.log(start .concat(end)); // result - “Open source”
var start= “Open ”;
var middle = “source”;
var end = “.”;
console.log(start .concat(middle, end)); // result - “Open source.”

Summary

We discussed most of string methods you can use in your work. Few were left untouched, however, the most useful of them were practiced through and through. Now, take a break for a while and then practice a bit until the next post. AD

If you liked this article, then please consider subscribing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.