How to Extract Part of Text from a String in JavaScript?

Estimated read time 1 min read

You can extract part of a text from a string in JavaScript by using the substring() or slice() methods.

Here’s an example using substring():

var str = "Hello, world!";
var sub = str.substring(0, 5);
console.log(sub);

In this example, the substring() method is used to extract the first five characters from the string stored in the str variable. The resulting substring is stored in the sub variable, which can be logged to the console or used elsewhere in your code.

Here’s an example using slice():

var str = "Hello, world!";
var sub = str.slice(0, 5);
console.log(sub);

In this example, the slice() method is used to extract the first five characters from the string stored in the str variable. The resulting substring is stored in the sub variable, which can be logged to the console or used elsewhere in your code.

Both substring() and slice() accept two arguments: the start index and the end index of the substring you want to extract. The start index is inclusive, while the end index is exclusive, meaning that the substring will include characters from the start index up to, but not including, the end index.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply