Mastering JavaScript Strings: Tips and Tricks for Effective Substring operations

Babandeep Singh
2 min readApr 26, 2023

As programmers, we frequently need to manipulate strings in our code. Thankfully, JavaScript provides a wealth of built-in methods that can assist us in working with arrays, strings, and other data types. These methods can be employed to perform a variety of tasks, such as searching, replacing, concatenating strings, and more.
Today we will be looking at different examples for string and substring in javascript

let mainString = 'Something happened to my thing when things were away and'+ 
'things were not things anymore';

let subString = 'thing'

// check if substring is available in main string

let checkSubStringPresence = mainString.includes(subString)

console.log(checkSubStringPresence) //true

let checkSubStringNotPresence = mainString.includes('subString')

console.log(checkSubStringNotPresence) //false

The example shown above will inform us whether the sub string exists or not.

//Get first index where substring is availabe

let firstIndexOfSubString = mainString.indexOf(subString)

console.log(firstIndexOfSubString) //4

The example shown above will inform us first instance of substring.

//Check How many time substring is present in main string

let getAllSubStringInstance = mainString.split(subString).length - 1

console.log(getAllSubStringInstance) //5

The example helps to determine the frequency of a substring in a given main string

// get all index of substring present in main string:

let getIndexesForSubString = [...mainString.matchAll(new RegExp(subString, 'gi'))].map(a => a.index);

console.log(getIndexesForSubString)

The example above retrieve all the indices of a substring that appears in a given main string

The content of this article was generated with the assistance of ChatGPT, Code is mine though.

--

--