How to remove text from a string in JavaScript?

JavascriptFront End TechnologyObject Oriented Programming

You can remove text from a string in Javascript using 2 methods, substring and replace.

Substring

JS string class provides a substring method that can be used to extract a substring from a given string. This can be used to remove text from either or both ends of the string.

Syntax

str.substr(start[, length])

Example

let a = 'Hello world'
console.log(a.substr(0, 5))
console.log(a.substr(6))
console.log(a.substr(4, 3))

Output

This will give the output −

Hello
world
o w

Replace

JS string class provides a replace method that can be used to replace a substring from a given string with an empty string. This can be used to remove text from either or both ends of the string.

Syntax

str.replace(old, new)

Example

let a = 'Hello world'
console.log(a.replace(" world", ""))
console.log(a.replace("Hello ", ""))
console.log(a.replace("o w", ""))

Output

This will give the output −

Hello
world
hellorld
raja
Published on 27-Nov-2019 10:13:40
Advertisements