How to Extract Values from Strings in JavaScript?

Estimated read time 1 min read

You can extract values from a string in JavaScript using various string methods such as substring, substr, and slice, or using regular expressions with the match method.

Here are a few examples:

Using substring:

let str = "Hello World!";
let result = str.substring(0, 5);
console.log(result);
// Output: "Hello"

Using substr:

let str = "Hello World!";
let result = str.substr(0, 5);
console.log(result);
// Output: "Hello"

Using slice:

let str = "Hello World!";
let result = str.slice(0, 5);
console.log(result);
// Output: "Hello"

Using Regular Expression match:

let str = "Hello World!";
let result = str.match(/Hello/);
console.log(result[0]);
// Output: "Hello"

In these examples, the substring, substr, and slice methods extract a portion of the string based on the start and end indices provided as arguments. The match method with a regular expression argument returns an array of all matches in the string. In this case, it returns an array containing one match, which is the first occurrence of the word “Hello” in the string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply