Sign up with your email address to be the first to know about new products, VIP offers, blog features & more.

 




How to remove text from string in JavaScript ?

JavaScript is widely used language. We may sometime need to remove text from string to get a desired output from certain API calls or even within an JavaScript APP. Answers to your question on how to remove text from string in JavaScript are mentioned below.

Removing Text using String.prototype.replace()

Using this method does not alter the original string but returns a new string.
For instance:

In order to remove all occurrences of the word “Hello” we can write following line.

Removing Text in JavaScript using slice() method

The slice()  method extracts parts of a string and returns the extracted parts as a new string. It takes two parameter which specify the parts of the string to be extracted.

Syntax: string.slice(start, end)

start: Specifies the position to begin the extraction. This parameter is mandatory. The first character is at position 0.

end: Specifies the position where the extraction should end. This parameter is optional and if not provided, slice() selects all characters from the start-position to the end of the string.

Here’s an example on how to remove text from string in JavaScript using slice()  method:

Extract from position 2

Providing both the parameters and extracting the string

We can give negative value to start parameter in order to start from the end of the string.

Custom method to delete word from string in JavaScript

JavaScript code to remove text from string and extract only Number

For this we’ll be using Regular Expression and match that to the given string and get the output as number. Here’s an example code snippet on how to remove text from string in JavaScript and extract number from the string.

Here’s what the statement above does…working middle-out:

  1. str.match(/\d+$/) – returns an array containing matches to any length of numbers at the end of str. In this case it returns an array containing a single string item [‘123’].
  2. Number()  – converts it to a number type. Because the array returned from .match() contains a single element Number() will return the number.

How to remove text inside brackets using Regular Expressions in JavaScript

Let’s jump straight into the code to learn how to remove text inside brackets using Regular Expressions in JavaScript.

Here, we are using regular expression  / *\([^)]*\) */g that finds the characters inside brackets (in this case small round brackets) and replace them with empty string.

References:

How to remove text from a string in JavaScript?

JavaScript/Regex : Remove Text inside Brackets

Thank you for your love.
share

No Comments Yet.

What do you think?

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

%d bloggers like this: