Reputation: 59
I have a long string that I'm trying to get one item which is the Stock#, if I could get it another way I could, but I'm stuck with:
Ingot Silver Metallic Exterior, Charcoal Black / Silver Stitch Interior, Status: Dealer Ordered, Engine: Regular Unleaded I-4 1.6 L/97, Trans: Automatic, Stock#: IP-2758P4B, VIN #: 3FADP4BJ2FM114457
So basically I just need IP-2758P4B. I've been trying different things from different answers from StackOverflow another place, but no luck.
Thank you in advance
Upvotes: 0
Views: 49
Reputation: 307
Regex in JavaScript is rather simple, but I really suggest you read a tutorial - there are tonnes on Google.
As for solving the problem with regex:
var a = "Ingot Silver Metallic Exterior, Charcoal Black / Silver Stitch Interior, Status: Dealer Ordered, Engine: Regular Unleaded I-4 1.6 L/97, Trans: Automatic, Stock#: IP-2758P4B, VIN #: 3FADP4BJ2FM114457";
var regex = /Stock#: (.+?),/g;
var resultArray = regex.exec(a);
if (resultArray.length >= 1) {
var result = resultArray[1];
} else {
// The stock number couldn't be found
}
Upvotes: 0
Reputation: 67988
Stock#: (\S+)
See Demo.It captures non space characters after Stock.
http://regex101.com/r/mU9cF1/1
Upvotes: 0
Reputation: 174806
You could try the below code,
> var foo = "Ingot Silver Metallic Exterior, Charcoal Black / Silver Stitch Interior, Status: Dealer Ordered, Engine: Regular Unleaded I-4 1.6 L/97, Trans: Automatic, Stock#: IP-2758P4B, VIN #: 3FADP4BJ2FM114457";
undefined
> var re = /Stock#:\s*([^,]*)/g;
undefined
> var m;
undefined
> while ((m = re.exec(foo)) != null) {
... console.log(m[1]);
... }
IP-2758P4B
Upvotes: 1
Reputation: 23863
Split is often easier to use than regular expressions:
Here is how I'd solve it.
var a = "Ingot Silver Metallic Exterior, Charcoal Black / Silver Stitch Interior, Status: Dealer Ordered, Engine: Regular Unleaded I-4 1.6 L/97, Trans: Automatic, Stock#: IP-2758P4B, VIN #: 3FADP4BJ2FM114457";
var stockNum = a.split("Stock#:")[1].split(",")[0].trim();
Upvotes: 1