Fun Never Ends With Javascript String Operations

Thiyagu Arunachalam
2 min readOct 3, 2023

--

Our Javascript string operation series comes to the third part. Please read the previous posts to get a hang of it. We will see how to search for a specific character in a given string.

Photo by Roman Synkevych on Unsplash

Find the position of the string:

In some cases, we need to find the position of the specific character in real-time programming. Javascript operation index-of is handy for finding the required string in a given text, and it returns that position.

let message  = "May the force be with you";
let indexMsg = message.indexOf("force");
console.log(indexMsg) //outputs --8--

This operation only provides the position of the first character in the string. We can also use last-index-of to find the last character’s location.

let message  = "May the force be with you. I'm not going to force you.";
let indexMsg = message.lastIndexOf("force");
console.log(indexMsg) //outputs --44--

We can also use the second parameter to tell the javascript in which position it needs to start searching. Both these method returns -1 if there’s no match.

let message  = "May the force be with you";
let indexMsg = message.indexOf("t",12);
console.log(indexMsg) //outputs --19--

String search:

Like the index-of operation, the string search operation checks the exact match of the string and returns a position. But, it only has a single parameter. So, we can’t skip some characters in a given text.

let lufi = "I'm going to be the king of the pirates"
let searchLufi = lufi.search("king");
console.log(searchLufi) //outputs --20--

String Match and Match All:

Another significant javascript string operation is match. This method returns an array(we will discuss this later) containing the first match to the given string.

let help = "You is kind. You is smart. You is important.";
let matched = help.match("You");
console.log(Array.from(matched));//outputs --["You"]--

We can get all matches using a match-all operation that returns an array with all the matching text parts from the given string.

let help = "You is kind. You is smart. You is important.";
let matched = help.matchAll("You");
console.log(Array.from(matched));//outputs --[... ]--

Starts With Ends With:

Using the Starts with and Ends with operations, we can test whether the text starts with the specific character or ends with the given character. These methods return a boolean.

let msg  = "Bond, James Bond";
let sMsg = msg.startsWith("Bond");//outputs true
let eMsg = msg.endsWith("Bond");//outputs true

That is all for today. See you soon with another spectacular article.

--

--

Thiyagu Arunachalam

Hi there! I'm a science and technology enthusiast with a passion for writing about the latest developments in the fields of science and coding.