Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Javascript regex (extract string)

Javascript regex (extract string)

Problem

I always forget how to create simple regular expressions despite doing projects with more complex regexes...

I have the string:

var s = "qwehref=\"1232.css\"qwasd asd asdqq eehref=\"asd.css\""

I want to capture the text inside the href tags: 1232.css and asd.css.

I've tried with this regex:

var re = /href="(.+\.css)"/g

but this is what I get (re.exec(s)):

'1232.css"qwasd asd asdqq eehref="asd.css'
Problem courtesy of: Gabriel Llamas

Solution

try

/href="([^"]+\.css)"/g

You don't want to match the closing quote as part of your file name. Or just use a non greedy match I guess...

/href="(.+?\.css)"/g
Solution courtesy of: David McMullin

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Javascript regex (extract string)

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×