Ask Your Question
4

What is the method in javascript to use regex for extracting a string between dashes?

asked 2022-12-31 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-12-23 00:00:00 +0000

woof gravatar image

The method in javascript to use regex for extracting a string between dashes is using the match() method with a regular expression that matches the string between the dashes.

const str = "hello-world";
const regex = /-(.*)-/;
const result = str.match(regex)[1];
// result will be "world"

In this example, the regular expression /-(.*)-/ matches any characters between two dashes. The match() method returns an array with the entire matched string, followed by the matched capturing groups. The [1] at the end of the expression extracts the first capturing group, which is the string between the dashes.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-31 11:00:00 +0000

Seen: 8 times

Last updated: Dec 23 '21