Apps/Gaming

JavaScript Methods for Searching Strings

Need to check whether a JavaScript string contains a specific character or substring? Or maybe you need to know where it appears in the string. In any event, JavaScript offers several ways to accomplish both these objectives. This web development tutorial will present an overview of the String’s many methods as well as some examples of how to use the string object’s methods dedicated to finding a substring within another string.

Reading: Top HTML and CSS Online Courses for Web Developers

JavaScript StringMethods

Take a look at the full list of string methods below and you will notice that there are more methods for searching than any other purpose, which highlights their importance:

searching

  • search(): searches for specified value in the string
  • indexOf(): returns the first index of occurrence of a value
  • lastIndexOf(): returns the last index of occurrence of a value
  • includes(): checks if given string is found inside a string
  • startsWith(): checks if a string begins with a specified string
  • endsWith(): checks if a string ends with a specified string
  • match(): returns result of matching string with a regex
  • matchAll(): returns iterator of results matching with a regex

trimming

  • trim(): removes whitespace from both ends of a string
  • trimStart(): removes whitespace from the beginning of a string
  • trimEnd(): removes whitespace from the end of a string

padding

  • padStart(): pads a string at the start to a given length
  • padEnd(): pads a string at the end to a given length

extraction

  • split(): returns the string divided into list of substring
  • substring()/substr(): return a specified part of the string
  • slice(): extracts and returns a section of the string

Concatenating

  • concat (): concatenates the arguments to the calling string

replacement

  • replace(): replaces a substring/pattern in the string
  • replaceAll(): returns string by replacing all matching patterns

Changing case

  • toUpperCase(): returns upper case of a string
  • toLowerCase(): returns lower case representation of a string

Characters and Unicode

  • charAt(): returns character at a specified index in string
  • charCodeAt(): returns Unicode of the character at given index
  • fromCharCode(): returns a string from the given UTF-16 code units
  • codePointAt(): returns the Unicode point value at given index
  • fromCodePoint(): returns a string using the given code points

Miscellaneous JavaScript String Search Methods

  • localeCompare(): compares two strings in the current locale
  • repeat(): returns a string by repeating it given times

Reading: Best Online Courses to Learn JavaScript

Working with the JavaScript String Object’s Search Methods

In this section of our JavaScript String method tutorial, we will go over each of the methods listed in the searching category above and cover their syntax and usage.

search()

the search() method matches a string against a regular expression or string searchValue. In the case of the latter, the string is converted to a regular expression by the method before proceeding with the search. the search() method returns the index (position) of the first match (starting from 0) or -1 if no match is found. the search() method is case sensitive unless the i flag is included in the regular expression.

Syntax of search() Method in JavaScript

string.search(searchValue)

Examples of search() Method in JavaScript

let text = “Please locate where ‘locate’ occurs!”; // 1st instance of “locate” document.writeln(text.search(“locate”)); // 7 text=”The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?”; // Any character that is not a word character or whitespace document.writeln(text.search(/[^ws]/G)); // 43 text = “Mr Blue has a blue house”; // Case insensitive search for “blue” document.writeln(text.search(/blue/i)); // 4

indexOf()/lastIndexOf() Method in JavaScript

the indexOf() other lastIndexOf() methods return the index of (position of) the first and last occurrence of a string in a string respectively or -1 if no match is found.

Syntax of indexOf()/lastIndexOf() Method

string.indexOf(searchValue) string.lastIndexOf(searchValue)

Examples of indexOf()/lastIndexOf() Method

let text = “Please locate where ‘locate’ occurs!”; text.indexOf(“locate”); // 7 text.lastIndexOf(“locate”); // 21 text.lastIndexOf(“text”); // -1 (not found)

The Difference Between search() and indexOf()

the search() other indexOf() methods are strikingly similar, albeit with a couple of notable differences:

  • the search() cannot take a start position argument.
  • the indexOf() method cannot search using a regular expression.

includes() Method in JavaScript

the includes() method returns true if a string contains a specified string value. Otherwise it returns false.

Syntax of includes() Method

string.includes(searchValue)

Examples of include() Method

let text = “Please locate where ‘locate’ occurs!”; text.includes(“locate”); // true text.includes(“find”); // false

Note that the includes() method is an ES6 feature and is not supported in Internet Explorer.

startsWith()/endsWith() Method in JavaScript

the startsWith() other endsWith() methods return true if a string begins or ends with a specified value, respectively. Otherwise, false is returned.

Syntax of startsWith()/endsWith() Method

string.startsWith(searchValue) string.endsWith(searchValue)

Examples of startsWith()/endsWith() Method

let text = “Please locate where ‘locate’ occurs!”; text.startsWith(“Please”); // true text.startsWith(“locate”); // false text.endsWith(“occurs!”); // true text.endsWith(“locate”); // false

Note that the startsWith() other endsWith() methods are an ES6 feature and are not supported in Internet Explorer.

match()/matchAll() Method in JavaScript

Both the match() other matchAll() methods return the results of matching a string against a supplied string or regular expression. The difference is that match() returns the results in an array while matchAll() returns an iterator. Introduced in ES6, iterators allow you to iterate over any object that follows the Iterator specification.

Syntax of match()/matchAll()

string.match(searchValue) string.matchAll(searchValue)

Examples of match()/matchAll()

let text = “Please locate where ‘locate’ occurs!”; text.match(“cat”); // [cat]
text.match(/cat/g); // [cat, cat]

text.matchAll(“occurs!”); // Iterator with 1 result text.matchAll(“locate”); // Iterator with 2 results

Note that the matchAll() method is an ES2020 feature and are definitely not supported in Internet Explorer.

Reading: Top Collaboration Tools for Web Developers

How to Invoke a String Method in JavaScript

The JavaScript string is a data type unlike any other in that it can be treated as either a primitive or object depending on whether it is assigned as a string literal or created using the thong constructor. Does that mean that primitive thongs do not have access to the thong object’s many useful methods? Not at all. Whenever a method is invoked on a primitive string, JavaScript will automatically wrap the string primitive and call the method on the wrapper object instead. So, however you create your strings, you can always access their methods.

You can see all of the methods from this tutorial in action in the codepen demo.

Final Thoughts on JavaScript Methods for Searching Strings

This web development tutorial presented an overview of JavaScript’s String’s many methods as well as some examples of how to use them. In the next installation, we will be taking a look at the trimming, padding, extracting, and concatenating methods of the thong objects. That will leave the remaining methods for the third and final installation.

Related posts

Getting started with Kotlin coroutines

TechLifely

Reaching a +40M playerbase: tips from Trihex Studios

TechLifely

Difference between var, let, and const in JavaScript

TechLifely

Leave a Comment