Wednesday, January 15, 2025
HomeProgrammingHow can I use JavaScript to extract a substring from a string?

How can I use JavaScript to extract a substring from a string?

In JavaScript, you can extract a substring from a string using methods like substring(), slice(), or substr() (though substr() is deprecated). Here’s how you can use each method:

1. Using substring(startIndex, endIndex)

Extracts characters between startIndex (inclusive) and endIndex (exclusive).

javascriptCopy code

const str = “Hello, World!”;

See also  Binary Search Algorithm - Iterative and Recursive ...

const result = str.substring(0, 5); // Extracts “Hello”

console.log(result);

2. Using slice(startIndex, endIndex)

Works similarly to substring(), but it supports negative indices to count from the end.

javascript

Copy code

const str = “Hello, World!”;

const result = str.slice(0, 5); // Extracts “Hello”

console.log(result);

const negativeResult = str.slice(-6); // Extracts “World!”

See also  Search a node in Binary Tree

console.log(negativeResult);

3. Using substr(startIndex, length)

Extracts a substring starting at startIndex with the specified length. Note that this method is deprecated.

javascript

Copy code

const str = “Hello, World!”;

const result = str.substr(0, 5); // Extracts “Hello”

console.log(result);

Recommendation: Use substring() or slice() as they are widely used and not deprecated.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x