Categories
JavaScript JavaScript Basics

How To Manipulate Strings in JavaScript

Spread the love

JavaScript has built-in functions and constructs to do most string operations. The ones that don’t can be done with a few simple function calls.


Combine Strings

Concatenation

There are two ways to do it. One way is to use the concat function.

For example:

const hello = "Hello ";  
const bob = "Bob!";  
const res = hello.concat(bob); // Hello Bob!

Another way is to use the + operator, like so:

const hello = "Hello ";  
const bob = "Bob!";  
const res = hello + bob; // Hello Bob!

Template strings

ES6 or later has template strings so you can include strings within another string, like this:

const hello = "Hello ";  
const bob = "Bob!";  
const res = `${hello} ${bob}`; // Hello Bob!

Array.join

If you have an array of strings, you can combine the entries with the same separator between them, with the join function, like this:

const arr = ['Hello', 'Bob'];  
const res = arr.join(' '); // 'Hello Bob'

Get Substring

String.substr

JavaScript strings have a substr function to get the substring of a string.

It takes a starting index as the first argument and a number of characters from the start index, and so on as the second argument.

It can be used like this:

const str = "Hello Bob";  
const res = str.substr(1, 4); // ello

String.substring

JavaScript strings also have a substring function that takes the start and end index as two arguments and returns a string with the ones between the start and end indices.

The start index is included but the end index is excluded.

Example:

const str = "Hello Bob";  
const res = str.substring(1, 3); // el

Changing Cases

String.toLocaleLowerCase()

Converts a string to lowercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";  
const res = str.toLocaleLowerCase(); // hello bob!

String.toLocaleUpperCase()

Converts a string to uppercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";  
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

String.toLowerCase()

Converts a string to lowercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";  
const res = str.toLocaleLowerCase(); // 'hello bob!'

String.toUpperCase()

Converts a string to uppercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";  
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

Removing Whitespace

String.trim()

Remove starting and ending white space from a string.

For example:

const str = "         Hello Bob!     ";  
const res = str.trim(); // 'Hello Bob!'

Remove all whitespaces from a string

There is no function to remove all whitespace from a string. We have to replace the spaces in the string with empty strings to do this.

For example:

const str = "         Hello Bob!     ";  
const res = str.replace(/ /g, ''); // 'HelloBob!'

Repeating Strings

There are a few ways to repeat a string in JavaScript. JavaScript strings have a built-in repeat() function.

You can also use a loop to do the same thing.

String.repeat Function

To use the repeat function, you pass in the number of times you want to repeat the string as an argument. It returns a new string.

For example:

const hello = "hello";  
const hello5 = A.repeat(5);  
console.log(hello5); // "hellohellohellohellohello"

Use a loop

You can use the for loop and while loop to perform repeatedly concatenate strings.

Using a for loop, you can do:

const hello = "hello";  
let hello5 = '';  
for (let i = 1; i <= 5; i++){  
  hello5 += hello;  
}  
console.log(hello5); // "hellohellohellohellohello"

With a while loop, you can do:

const hello = "hello";  
let hello5 = '';  
let i = 1;  
while(i <= 5){  
  hello5 += hello;  
  i++  
}  
console.log(hello5); // "hellohellohellohellohello"

They both involve increment indexes up to the maximum.


Search

There are a few ways to search for strings in JavaScript.

Strings have the startsWith, endsWith, indexOf, lastIndexOf, charAt, search, includes, and match functions.

startsWith

startsWith checks if a string starts with the substring you pass in.

For example:

const str = "Hello world.";  
const hasHello = str.startsWith("Hello"); // trueconst str2 = "Hello world.";  
const hasHello2 = str.startsWith("abc"); // false

endsWith

endsWith checks if a string ends with the substring you pass in.

For example:

const str = "Hello world.";  
const hasHello = str.endsWith("world."); // trueconst str2 = "Hello world.";  
const hasHello2 = str.endsWith("abc"); // false

indexOf

indexOf finds the index of the first occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";  
const hasHello = str.indexOf("Hello"); // 0  
const hasHello2 = str.indexOf("abc"); // -1

lastIndexOf

lastIndexOf finds the index of the last occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";  
const hasHello = str.lastIndexOf("Hello"); // 6  
const hasHello2 = str.lastIndexOf("abc"); // -1

charAt

charAt returns the character located at the index of the string.

For example:

const str = "Hello";  
const res = str.charAt(0); // 'H'

search

search gets the position of the substring passed into the function. It returns -1 if the substring is not found in the string.

Example:

const str = "Hello";  
const res = str.search('H'); // 0

includes

includes checks if the passed-in substring is in the string. Returns true if it is in the string, false otherwise.

const str = "Hello";  
const hasH = str.includes('H'); // true  
const hasW = str.includes('W'); // false

Replace

The replace() function, included with strings, is useful for replacing parts of strings with another. It returns a new string with the string after the substring is replaced.

Example:

const str = "Hello Bob";  
const res = str.replace("Bob", "James"); // 'Hello James'

replace() can also be used to replace all occurrences of a substring.

For example:

const str = "There are 2 chickens in fridge. I will eat chickens today.";  
const res = str.replace(/chickens/g, "ducks"); // "There are 2 chickens in fridge. I will eat chickens today."

If the first argument is a regular expression that searches globally, it will replace all occurrences of the substring.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *