BLOGS
Welcome to the world of Javascript Strings…. In this article, we will walkthrough different types of string functions which seems to be the bread and butter of a Javascript developer (be it a frontend engineer or be it a backend engineer).
How to find the length of a string? We often encounter this scenario as a Javascript developer! The string length can be found out using the length property.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.length console.log(result);
This snippet prints the number “31”, which gives the total count of characters(including whitespaces) of the “sentence” string variable defined by enclosing parentheses.
Have you ever wondered what would be the most viewed questions regarding Javascript strings in StackOverflow?
Much to our surprise, this question has been viewed more than 5.8 million times by developers all over the globe.And the question is related to substring in Javascript!!!!
Ok.Let’s break the suspense…. The question is
“How to check whether a string contains a substring in JavaScript?”
So, the main purpose behind this much stats is to elaborate on the importance of the substring function that has been actively hunted for years in the Javascript fraternity.
Prior to ES6, the answer to the question had been lying in the hands of the function,indexOf()
Well, let’s go into the details of the syntax for these functions.
Searches and (if found) returns the index number of first occurrence of the searched character or substring within the string. If not found, -1 is returned. “Start” is an optional argument specifying the position within string to begin the search. Default is 0.
So, for finding the occurence of a substring inside a string, we use the following logic:
const sentence="Hi,I am a Javascript Developer!" if (sentence.indexOf("Javascript")!=-1) { console.log("He is a Javascript Developer!") }
const sentence = "Hi,I am a Javascript Developer!"; let result = sentence.indexOf('Hi'); console.log(result)
But in the post-ES6 era, this function was dethroned by the much more powerful one namely,includes() but still indexOf() is used in IE browser, since it doesn’t provide support for the includes() function.
The only difference between indexOf and includes is that the latter returns a boolean value while the former returns the starting index of the substring, if found and otherwise it returns -1.
const sentence="Hi,I am a Javascript Developer!" if (sentence.includes("Javascript")) { console.log("Substring Found"); } else { console.log("Substring not found"); }
const sentence="Hi,I am a Javascript Developer!" if (sentence.includes("xyz")) { console.log("Substring Found"); } else { console.log("Substring not found"); }
This snippet prints “Substring not found”.
Searches (if found) returns the index number of the last occurrence of the searched character or substring within the string. If not found, -1 is returned.
const sentence="Hi,I am a Javascript Developer!"; // 'H','i',',',' ','I',' ','a','m',' ','a',' ','J','a','v','a' let result = sentence.lastIndexOf("a"); console.log(result)
This snippet prints “13”
That’s great. Now, let’s move onto the next faction in string functions which is used in extracting part of string as a separate one.
Returns the characters in a string between “start” and “end” indexes, NOT including “end” itself. “end” is optional, and if omitted, up to the end of the string is assumed.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.substring(10,20); console.log(result);
This snippet prints “Javascript”.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.substring(10); console.log(result);
And, this snippet prints “Javascript Developer!”
Returns the characters in a string beginning at “start” and through the specified number of characters, “length”. “Length” is optional, and if omitted, up to the end of the string is assumed.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.substr(10); console.log(result);
This snippet prints “Javascript Developer!”,
This method accepts negative indices for the “start” parameter.
Note: For correct manipulation of negative indices, imagine that the index starts from the end of the string as -1 and goes on till the start.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.substr(-10); console.log(result);
This snippet prints “Developer!”
In substr() method, we need to specify the length of characters to be extracted as the second parameter.
But in the case of substring() method, the second parameter holds the index of the character upto which the text has to be extracted.(non-inclusive index)
The slice method is similar to the substring method except for the fact that it can accept negative indices as parameters which the latter doesn’t support.
As mentioned earlier,in the case of negative indices,the characters are counted from the end of the string.
In the positive indices scenario, if the start is greater than end, then an empty string is returned.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.slice(3,1); console.log(result);
In the negative indices scenario, if the end is smaller than start, then it returns an empty string.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.slice(-10,-15); console.log(result);
There is a method called “Splice()”, which is a destructive method pertaining to Array objects that manipulates the original array instead of creating a clone to do the manipulation.
Don’t confuse “slice()” with “Splice()”. Splice() method exists only for Array however slice() method exists for both arrays as well as strings.
In due course, we will see a method that can be used to convert string to Array consisting of characters based on certain conditions. Henceforth, we can use splice() method on strings after converting them as arrays.
Now, it’s time to garner our attention towards the methods available for manipulating the strings.
Splits a string into many substrings according to the specified delimiter, and returns an array containing each element. The optional “limit” is an integer that lets you specify the maximum number of elements to return.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.split(' '); console.log(result);
This snippet prints the below array as we have split based white space as a delimiter
[ ‘Hi,I’, ‘am’, ‘a’, ‘Javascript’, ‘Developer!’ ]
Note: If we use sentence.split(”),we can get an array containing all the characters in the string.
concat() method joins two strings.It is the actual replacement for ‘+’ operator for concatenating strings. The concat() method needs a string instance to be used and accepts as many as strings to be concatenated with the calling instance.
const sentence="Hi,I am"; const nextSentence = "a Javascript Developer!"; let result = sentence.concat(" ",nextSentence); console.log(result);
This snippet prints “Hi,I am a Javascript Developer!”
trim() method is used to remove whitespaces and other line terminator characters from the leading and trailing ends of a string.
It doesn’t care about the whitespaces and characters in between the words present in the string. Also, trim() doesn’t accept any function arguments.
const sentence=" Hi,I am a Javascript Developer! "; let result = sentence.trim(); console.log(result);
const sentence=" Hi,I am a Javascript Developer! \n \r \t"; let result = sentence.trim(); console.log(result);
Both snippet prints “Hi,I am a Javascript Developer!”
const sentence=" Hi,I am a \n Javascript Developer! \n \r \t"; let result = sentence.trim(); console.log(result);
This snippet prints the following:
“Hi,I am a
Javascript Developer!”
As the name suggests, these methods are used to convert the case of the letters present in the string.
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.toLowerCase(); console.log(result);
This snippet prints “hi,i am a javascript developer!”
const sentence="Hi,I am a Javascript Developer!"; let result = sentence.toUpperCase(); console.log(result);
This snippet prints “HI,I AM A JAVASCRIPT DEVELOPER!”
The easiest way to convert a string to a number is to use Number() constructor method.
let str = '22'; console.log(typeof str) // prints string let num = Number(str); console.log(typeof num); // prints number
Note: Be wary of using ‘+’ operator in the context of strings and numbers. Because, while using ‘+’ operator, strings will be concatenated before being converted to number type.
toString() method is particularly useful when converting numbers from one radix base to another. It accepts the radix number argument and returns string pertaining to corresponding base.
By default, base = 10(decimal system). The base can vary from 2 to 36;
let num = 255; console.log(num.toString(2)); console.log(num.toString()); console.log(num.toString(8)); console.log(num.toString(16));
This snippet prints the following:
11111111
255
377
ff
search() method returns a boolean value if a pattern matching the regex is found in the string. For example, in the below snippet,we are trying to find numbers in a string.
let str = "There are 25 books in the shelf" if (str.search(/\d/gi)) { console.log("Number found in the string"); }
This snippet prints “Number found in the string” since the condition is true.
Note: Regex is a topic that can be covered as a separate blog and currently not in the scope of this blog. Please feel free to go through this link for your intuitive understanding.
The contrasting fact between match() and search() is that the former returns the matching values as an array(if no matching values, null is returned) while the latter returns a boolean value based on the fact whether a match is found or not according to the given regex.
let str = "There are no books in shelf" let values = (str.match(/\d/gi)) console.log(values);
This snippet prints ‘null’
let str = "There are 25 books in shelf" let values = (str.match(/\d/gi)) console.log(values);
This snippet prints [ ‘2’, ‘5’ ]
replace() method is an extension to match(), and it can be used when we want to search and replace an occurence in a string.
const str = "There are 25 boks in shelf. All boks are pertaining to Javascript" let newStr = str.replace(/boks/gi,"books") console.log(newStr);
Since, the sentence contains a typo,we are replacing the correct spellings.
This snippet prints the following:
“There are 25 books in shelf. All books are pertaining to Javascript”.
BLUECAST TECHNOLOGIES PTE LTD,
31 SIMEI RISE, 528779 SINGAPORE
BLUECAST TECHNOLOGIES LLC P.O. Box: 128274, DUBAI
UNITED ARAB EMIRATES
BLUECAST TECHNOLOGIES PVT. LTD, KAKKANAD P.O.
KOCHI, 682030, INDIA
Email : info@bluecast.ae
Phone: +91 830 400 8000