Sitemap

String JavaScript Methods

5 min readSep 1, 2024

--

In JavaScript, string are a fundamental data type used to represent text. When working with strings, you often need to perform various operations like concatenaton, searching, replacing, and more. JavaScript provides a wide range of string methods to make tasks easier. In this article, we will explore the most commonly used JavaScript string methods.

Press enter or click to view image in full size

1. Searching and Matching Methods

  • includes() : Checks if the string contains as specified value and Return in Boolean.

Syntax:

includes(searchString)
includes(searchString, position)

Example :

const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.includes('fox')); //true

console.log(sentence.includes('q')); //true

console.log(sentence.includes('quk')); //true
  • indexOf() : Returns the index of the first occurrence of a specified value. It Return index value if element found, otherwise return -1;

Syntax:

indexOf(searchString)
indexOf(searchString, position)Example :

const sentence = "The quick brown fox jumps over the lazy dog.";

console.log(sentence.indexOf("fox")); // 16

console.log(sentence.indexOf('q',16)); //-1 (because q is not found after 16th index);
  • lastIndexOf() : Returns the index of the last occurrence of a specified value.

Syntax :

array.lastIndexOf(searchElement)
array.lastIndexOf(searchElement, fromIndex)

Example :

const sentence = "The quick brown fox jumps over the lazy fox.";

console.log(sentence.lastIndexOf("fox")); // 40
  • match() : Seaches for matched in the string using a regular expression.

Syntax :

match(regexp)

Example :

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found); // output: Array ["T", "I"]

//Extract all email addresses from a string.
const text = "Contact us at support@example.com or sales@example.com.";

console.log(text.match(/[\w]+@[\w]+\.[\w]+/g)); // ["support@example.com", "sales@example.com"]
  • matchAll() : Returns an iterator for all matches in the string using a regular expression.

Syntax :

matchAll(regexp)

Example :

// Extract all URLs from a string.
const text = "Visit https://www.google.com or https://www.github.com";
const urls = [...text.matchAll(/https?:\/\/\S+/g)];
console.log(urls);
/*
Output :
[
[
'https://www.google.com',
index: 6,
input: 'Visit https://www.google.com or https://www.github.com',
groups: undefined
],
[
'https://www.github.com',
index: 32,
input: 'Visit https://www.google.com or https://www.github.com',
groups: undefined
]
]
*/

  • search() : Searches for the first match in the using a regular expression.

Syntax :

search(regexp)

Example :

const sentence = "The quick brown fox jumps over the lazy dog.";

console.log(sentence.search(/fox/)); // 16

2. Manipulation Methods

  • charAt() : Returns the character at a speacified index.

Syntax :

charAt(index)

Example :

const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.charAt(4)); //'q'
  • charCodeAt() : Returns the Unicode code point at a specified index.

Syntax :

charCodeAt(index)

Example :

//Get the Unicode code point of the first character of a string.
const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.charCodeAt(4)); //113
  • codePointAt() : Returns the Unicode code point at a specified index.

Synatx :

codePointAt(index)

Example :

//Get the Unicode code point of the first character of a string.
const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.codePointAt(4)); //113
  • concat() : Concatenates two or more strings.

Syntax :

concat()
concat(str1)
concat(str1, str2)
concat(str1, str2, /* …, */ strN)

Example :

//Concatenate two strings.
const str1 = 'Hello';
const str2 = 'World';

console.log(str1.concat(' ', str2)); //"Hello World"

console.log(str2.concat(', ', str1)); //"World, Hello"
  • replace() : Replaces a specified value with another value.

Syntax :

replace(pattern, replacement)

Example :

const text = "The quick brown fox jumps over the fox lazy dog.";

console.log(text.replace(/fox/g, "cat")); // "The quick brown cat jumps over the cat lazy dog."
  • replaceAll() : Replaces all occurrences of a specified value with another value.

Syntax :

replaceAll(pattern, replacement)

Example :

//Replace all occurrences of a word in a string.
const text = "The quick brown fox jumps over the lazy fox.";

console.log(text.replaceAll("fox", "cat")); // "The quick brown cat jumps over the lazy cat."
  • slice() : Extracts a substring from the string.

Syntax :

slice(indexStart)
slice(indexStart, indexEnd)

Example :

// Extract a substring from a string.

const str = "Hello World";
console.log(str.slice(6)); // "World"
  • split() : Split the string into an array of substring.

Syntax :

split(separator)
split(separator, limit)

Example :

Get Prince kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

// Split a string into an array of substrings.

const str = "Hello,World,JavaScript";
console.log(str.split(",")); // ["Hello", "World", "JavaScript"]
  • substring() : Extracts a substring from the string.

Syntax :

substring(indexStart)
substring(indexStart, indexEnd)

Example :

//Extract a substring from a string.

const str = "Hello World";
console.log(str.substring(6)); // "World"

3. Normalization and Case Methods

  • normalize() : Normalizes the string to a specified Unicode normalization form.

Syntax :

normalize()
normalize(form)

Example :

//Normalizes the string to a specified Unicode normalization form.

const str = "cafe\u0301"; // cafe with combining acute accent
console.log(str.normalize("NFC")); // "café"
  • toLocaleLowerCase() : Converts the string to lowercase using the host environment’s current locale.

Syntax :

toLocaleUpperCase()
toLocaleUpperCase(locales)

Example :

//Converts the string to lowercase using the host environment's current locale.
const str = "HELLO";
console.log(str.toLocaleLowerCase()); // "hello" (or "hëllo" in some locales)
  • toLocaleUpperCase() : Converts the string to uppercase using the host environment’s current locale.

Syntax :

toLocaleUpperCase()
toLocaleUpperCase(locales)

Example :

//Converts the string to uppercase using the host environment's current locale.
const str = "hello";
console.log(str.toLocaleUpperCase()); // "HELLO" (or "HËLLO" in some locales)
  • toLowerCase() : Converts the string to lowercase.

Syntax :

toLowerCase()
//Converts the string to lowercase.
const str = "HELLO";
console.log(str.toLowerCase()); // "hello"
  • toUpperCase() : Concerts the string to uppercase.

Syntax :

toUpperCase()

Example :

//Converts the string to uppercase.
const str = "hello";
console.log(str.toUpperCase()); // "HELLO"

4. Timming and Padding Methods

  • trim() : Removes whitesapce from the beginning and end of the string.

Syntax :

trim()

Example :

//Remove whitespace from the beginning and end of a string.

const str = " Hello World ";
console.log(str.trim()); // "Hello World"
  • trimEnd()/trimRight() : Removes whitespace from the end of the string.

Syntax :

trimEnd()

trimRight()

Example :

//Remove whitespace from the end of a string.
const str = "Hello World ";
console.log(str.trimEnd()); // "Hello World"
  • trimStart()/trimLeft() : Removes whitespace from the beginning of the string.

Syntax :

trimStart()

trimLeft()

Example :

//Remove whitespace from the beginning of a string (alias for trimStart()).
const str = " Hello World";
console.log(str.trimLeft()); // "Hello World"
  • padEnd() : Pads the string with a specified value to a specified length.

Syntax :

padEnd(targetLength)
padEnd(targetLength, padString)

Example :

//pad a string with a specified value to a specified length.
const str = "Hello";
console.log(str.padEnd(10, "*")); // "Hello*****"
  • padStart() : Pads the string with a specified value to a specified length.

Syntax :

padStart(targetLength)
padStart(targetLength, padString)

Example :

//Pad a string with a specified value to a specified length.
const str = "Hello";
console.log(str.padStart(10, "*")); // "*****Hello"

6. Miscellaneous Methods

  • at() : Returns the character at a specified index. (same as charAt()).

Syntax :

at(index)

Example :

//Returns the character at a specified index.

const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.at(5))
  • toString() : Returns the string as string value.

Syntax :

toString()

Example :

//Returns the string as a string value.
const str = "Hello";
console.log(str.toString()); // "Hello"
  • valueOf() : Returns the primitive value of the string.

Syntax :

valueOf()

Example :

//Returns the primitive value of the string.

const str = "Hello";
console.log(str.valueOf()); // "Hello"

In this article, we’ve covered the most commonly used JavaScript string methods. Mastering these methods will help you work with strings more efficiently and effectively. Whether you’re a beginner or an experienced developer, understanding these methods is essential for building robust and maintainable JavaScript applications.

--

--

Prince kumar
Prince kumar

Written by Prince kumar

0 followers

MERN Developer | Leveling Up with Data Structures & Algorithms