How to tell if a String contains a Substring in Javascript

0 min read 136 words

Javascript comes with some pretty good support for determining if a string contains a substring.

There is the newer includes function which was introduced in ES2015 which allows you to tell if a string contains a substring. This function returns a boolean value of true or false.

'our example string'.includes('example')

// returns true

Alternatively, if you need to either:

  • Have support for older versions of Javascript
  • Need to not only know if a string contains a substring, but also it’s position within the string..

Then indexOf is a better match for you.

It works as follows:indexOf(search_string, position)

The second argument, position, is not mandatory as shown in the below examples:

'our example string'.indexOf('example') !== -1

// returns true

'our example string'.indexOf('example', 7) !== -1

// returns false

'our example string'.indexOf('example', 2) !== -1

// returns true
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags