DEV Community

Cover image for Common Built-in String Methods in Javascript
Femi Akinyemi
Femi Akinyemi

Posted on

Common Built-in String Methods in Javascript

String

According to MDN Web Docs,

The String object is used to represent and manipulate a sequence of characters.

It would be impossible to write code without using a string. Strings are a part of every programmer's life.

For manipulating strings, JavaScript provides various functions and methods.

With these methods, developers can modify string values, determine character indexes, and change string cases. And so on.

This article will show some commonly used methods for manipulating strings in JavaScript:

includes()

includes() method lets us determine whether or not a string includes another string.

Syntax

str.includes(searchString, position);
Enter fullscreen mode Exit fullscreen mode

Parameters

searchString
String to search within str. Regex cannot be used.

position
In the string, the location at which to begin searching for searchString. The default value is 0.

Example

const sentence = "The dog is mine";

const word = "dog";

console.log(
  `The word "${word}" ${
    sentence.includes(word) ? "is" : "is not"
  } in the sentence`
);
// expected output: "The word "dog" is in the sentence"
Enter fullscreen mode Exit fullscreen mode

charAt()

The charAt() method returns a character in a string at a specific index (position).
The first character has an index of 0 the second has an index of 1

Syntax

str.charAt(index);
Enter fullscreen mode Exit fullscreen mode

Example

const sentence = "The house is mine";

const index = 4;

console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// expected output: "The character at index 4 is h"
Enter fullscreen mode Exit fullscreen mode

concat()

The concat() method combines strings (str1, str2, /_ …, _/ strN) into one. Upon concatenating the string arguments, it returns a new string.

Syntax

str.concat(str2);
str.concat(str2, str3);
str.concat(str2, str3, ... , strN);

Enter fullscreen mode Exit fullscreen mode

Example

const str1 = "Text";
const str2 = "Book";

console.log(str1.concat(" ", str2));
// expected output: "Text Book"

console.log(str2.concat(", ", str1));
// expected output: "Text, Book"
Enter fullscreen mode Exit fullscreen mode

endsWith()

The endsWith() method returns true if a string ends with a specified string. Otherwise, it returns false.

Syntax

str.endsWith(searchvalue, length);
Enter fullscreen mode Exit fullscreen mode

Example

const str1 = "Dogs are the best!";

console.log(str1.endsWith("best!"));
// expected output: true

console.log(str1.endsWith("best", 17));
// expected output: true

const str2 = "Are you ok?";

console.log(str2.endsWith("ok"));
// expected output: false
Enter fullscreen mode Exit fullscreen mode

indexOf()

The indexOf() method returns the position of the first occurrence of a value in a string.

If the value cannot be found, indexOf() returns -1.

It is important to note that indexOf() is case sensitive.

Syntax

str.indexOf(searchvalue, position);
Enter fullscreen mode Exit fullscreen mode

Parameters

searchString
Substring to search for.

position
In cases where position exceeds the length of the calling string, the method skips the calling string altogether. Methods treat position less than zero as if it were 0.

Example

const myString = "Hello World";
const myCapString = "Hello Nigeria";

console.log(`myString.indexOf("World") is ${myString.indexOf("World")}`);
// logs 6
console.log(`myCapString.indexOf("World") is ${myCapString.indexOf("World")}`);
// logs -1
Enter fullscreen mode Exit fullscreen mode

lastIndexOf()

In a string, lastIndexOf() returns the last occurrence (position) of a value.
A string is searched from the end to the beginning using the lastIndexOf() method.
lastIndexOf() method returns the index from the beginning (position o).

Syntax

str.indexOf(searchvalue, position);
Enter fullscreen mode Exit fullscreen mode

Parameters

searchString
Substring to search for.

position

As a default, position is defaulted to +Infinity, which is the index of the last instance of the specified substring.

Example

const paragraph = "In the end, we all felt like we ate too much.";

const searchTerm = "ate";

console.log(
  `The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(
    searchTerm
  )}`
);
// expected output: "The index of the first "ate" from the end is 32"
Enter fullscreen mode Exit fullscreen mode

repeat()

The repeat() method returns a new string containing the number of concatenated copies of the string that was passed in.

Syntax

str.repeat(count);
Enter fullscreen mode Exit fullscreen mode

Example

const chorus = "until the night is over. ";

console.log(
  `Chorus lyrics for "I wanna be in your life until the night is over": ${chorus.repeat(
    7
  )}`
);

//Chorus lyrics for "I wanna be in your life until the night is over": until the night is over. until the night is over. until the night is over. until the night is over. until the night is over. until the night is over. until the night is over.
Enter fullscreen mode Exit fullscreen mode

replace()

replace() method searches for values in a string or regular expressions in a string.

The replace() method returns a newly created string with the replaced value(s).

replace() does not alter the original string.

Syntax

str.replace(pattern, replacement);
Enter fullscreen mode Exit fullscreen mode

Parameters

pattern
A regular expression is a typical example of a string or an object with the Symbol.replace method. Values without the Symbol.replace method will be converted to strings.

replacement

This can be a string or a function.

Example

const p = "The envelope is bad";

console.log(p.replace("is", "was"));
// The envelope was bad

const regex = /The/i;
console.log(p.replace(regex, "My"));
// My envelope is bad
Enter fullscreen mode Exit fullscreen mode

search()

The search() method searches for a word in the string and returns its index. If no match is found, it returns -1.

It is important to note that search() is case sensitive.

Syntax

str.search(searchValue);
Enter fullscreen mode Exit fullscreen mode

Example

let text = "Mr. Ben has a blue car";
let position = text.search("Ben");

console.log(position);

// logs 4
Enter fullscreen mode Exit fullscreen mode

slice()

The slice() method returns a new string containing a section of a string without altering the original string.

Syntax

str.slice(indexStart);
str.slice(indexStart, indexEnd);
Enter fullscreen mode Exit fullscreen mode

Parameters

indexStart
This is the index of the first character to include in the returned substring.

indexEnd
This is the index of the first character to exclude in the returned substring.

Example

let str = "Welcome to Nigeria";

console.log(str.slice(11));
// expected result: "Nigeria"

console.log(str.slice(8, 11));

// expected result: "to"
Enter fullscreen mode Exit fullscreen mode

split()

The split() method creates an ordered list of substrings from a string. A string will be split into many parts
according to the seperator specified, and each element is returned as an array.

Syntax

str.split();
str.split(separator);
str.split(separator, limit);
Enter fullscreen mode Exit fullscreen mode

Parameters

separator Optional
This pattern describes where each split should occur.

limit Optional
A non-negative integer specifying the maximum number of substrings to include in the array.

Example

let str = "Nigeria is an African country";

let words = str.split(" ");
console.log(words);

// expected result : [ 'Nigeria', 'is', 'an', 'African', 'country' ]

let chars = str.split("");
console.log(chars[0]);

// expected result "N"

let strCopy = str.split();
console.log(strCopy);
//expected result : [ 'Nigeria is an African country' ]
Enter fullscreen mode Exit fullscreen mode

startsWith()

The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false.

Syntax

str.startsWith(searchString);
str.startsWith(searchString, position);
Enter fullscreen mode Exit fullscreen mode

Parameters

searchString
The characters to be searched for at the beginning of this string. It cannot be a regex.

position Optional

A position at which searchString should be found (the index of searchString's first character). The default value is 0.

Example

const str1 = "Yesterday was my birthday";

console.log(str1.startsWith("Y"));
// expected output: true

console.log(str1.startsWith("Yes", 3));
// expected output: false
Enter fullscreen mode Exit fullscreen mode

substring()

The substring() method returns the part of the string between the start and end indexes or to the end.

Syntax

str.slice(indexStart);
str.slice(indexStart, indexEnd);
Enter fullscreen mode Exit fullscreen mode

Parameters

indexStart

This index represents the first character in the returned substring.

indexEnd
This is the index of the first character to exclude in the returned substring.

Example

const str = "Breakfast";

console.log(str.substring(1, 3));
// expected output: "re"

console.log(str.substring(5));
// expected output: "fast"
Enter fullscreen mode Exit fullscreen mode

toLocaleLowerCase()

It converts a string to lowercase letters according to the current locale.

Browser language settings determine the locale.

toLocaleLowerCase() does not change the original string

Except for locales (such as Turkish) that conflict with regular Unicode case mappings, toLocaleLowerCase() returns the same result as toLowerCase()

Syntax

str.toLocaleLowerCase();
str.toLocaleLowerCase(locales);
Enter fullscreen mode Exit fullscreen mode

Parameters

locales optional
An array of strings containing BCP 47 language tags.

Example

let text = "Hello Nigeria!";
let result = text.toLocaleLowerCase();
console.log(result); // Expected: hello nigeria!
Enter fullscreen mode Exit fullscreen mode

toLocaleUpperCase()

It converts a string to uppercase letters according to the current locale.

Browser language settings determine the locale.

toLocaleUpperCase() does not change the original string

Except for locales (such as Turkish) that conflict with regular Unicode case mappings, toLocaleUpperCase() returns the same result as toUpperCase()

Parameters

locales optional
An array of strings containing BCP 47 language tags.

Example

let text = "Hello Nigeria!";
let result = text.toLocaleUpperCase();
console.log(result); // Expected: HELLO NIGERIA!
Enter fullscreen mode Exit fullscreen mode

toString()

toString method returns a string as a string.
toString method does not change the original string.
The toString method converts a string object to a string.

Syntax

str.toString();
Enter fullscreen mode Exit fullscreen mode

Example

let text = "Hello Nigeria!";
let result = text.toString();

console.log(result); // Hello Nigeria
Enter fullscreen mode Exit fullscreen mode

trim()

The trim() method removes the whitespace from both ends of a string and returns a new one.

Syntax

str.trim();
Enter fullscreen mode Exit fullscreen mode

Example

const greeting = "   Hello Nigeria!   ";

console.log(greeting);
// expected output: "   Hello Nigeria!   ";

console.log(greeting.trim());
// expected output: "Hello Nigeria!";
Enter fullscreen mode Exit fullscreen mode

valueOf()

The valueOf() method returns a primitive value for a String.

Syntax

str.valueOf();
Enter fullscreen mode Exit fullscreen mode

Example

let text = "Hello Nigeria!";
let result = text.valueOf();

console.log(result); // Hello Nigeria!
Enter fullscreen mode Exit fullscreen mode

This concludes the list of commonly used methods in JavaScript. I hope you can use some of these for your projects.

Please, let me know what you think in the comment section.

Thanks for Reading 🌟🎉

I'd love to connect with you on Twitter

On to another blog, some other day, till then Femi👋.

Useful Resources

Top comments (0)