LinA LinA - 1 year ago 156
Javascript Question

Javascript, Using regex to extract values from a string

Hey guys I was wondering how to go about using regex to extract specific values from a string?

For example:

var str = `<script type='text/javascript'>
if (!true) { var arr=[];}
arr.push({ 'id': '123' });
<script type='text/javascript' src='img.jpg'></script>`;

How would the regex expression look like to extract the value stored in id and the src? 123 and img.jpg

Answer Source

You can extract the id using this regex:


Using it this way:

var matches = str.match(/'id'\s*:\s*'(\d+)'/i)

The value 123 will be contained in matches[0].

You can extract the img.jpg value with this regex:


You can use it this way:

var matches = str.match(/src\s*=\s*["']([^"'>]+)["']?/i)

and the value 'img.jpg' will be contained in matches[0].

Note that the contents of the string provided isn't valid HTML, as it's missing the final quote after img.jpg. The regex takes this into account in case that was the purpose.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download