Majix
Majix

Reputation: 568

using regular expression in javascript to return some part of words that start with a specific pattern

Given a string containing several strings delimited by spaces, I'm trying to find the one that starts with "dtl-" and then return only the part of the matched word that comes after "dtl-" (in this case they are digits)

For example, if the string is:

class = "odd dtl-78634 blue active";

then I need to return:

"78634"

When I use the following code:

var id = class.match(/dtl-(\d+)/);

id will be an array containing two values: "dtl-78634" and "78634"

I can use id[1] which will hold my desired value, but my questions are:

1) Why am I receiving two different matches? One including what I call the "signature" (in this case "dtl-"), and the other one does not include the signature.

2) Is there a way in regular expression to specifically generate one of the two types of returned matches?

Thank you.

Upvotes: 0

Views: 79

Answers (2)

The Dark Knight
The Dark Knight

Reputation: 5585

It should not be that difficult. And i don't think you need regex to do this. Simple split will do the job for you.

Consider a simple logic. First split the variable using - and then split using empty space like this :

var idT = "odd dtl-78634 blue active";
var arrayIDT = idT.split("-");
console.log(arrayIDT[1]);
var id = arrayIDT[1].split(" ");
console.log(id[0]);

Find the working fiddle here : http://jsfiddle.net/FXhLx/

Upvotes: 0

Yozer
Yozer

Reputation: 648

id[0] will contain the text that matched the full pattern, id[1] will have the text that matched the first captured string.

Upvotes: 1

Related Questions