0

I'm trying to figure out how can I extract a URL from the following string in JS.

var str = '[velocity type="youtube" id="239793212" img="http://website.com/wp-content/uploads/image-placeholder.jpg" alt="Play" color="#FFFFFF" bkg_color="transparent"]';

I would like to somehow pull only the http://website.com/wp-content/uploads/image-placeholder.jpg value from this WordPress shortcode which is being read by the WordPress TinyMCE editor.

I should add that the string will not always be in the exact format and the position of img="" will fluctuate.

Is there a way to parse this string as JSON or an array so I can access the value of img?

Darren Cooney
  • 1,012
  • 16
  • 25

3 Answers3

4
/img="([^"]*)"/.exec(str)[1]

In English: Create a regular expression that matches the img part, put the URL in group 1 and after executing the expression on the string, get the contents of group 1.

The expression breaks down as

img="        # the string 'img="'
(            # begin group 1
  [^"]*      #   any character that is not a '"', any number of times
)            # end group 1
"            # the final double quote

Relevant documentation: RegExp.prototype.exec() on the MDN and of course the primary info site on regular expressions: http://www.regular-expressions.info/.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
1

A not so OO way to do it:

var str = '[velocity type="youtube" id="239793212" img="http://website.com/wp-content/uploads/image-placeholder.jpg" alt="Play" color="#FFFFFF" bkg_color="transparent"]';

var url = null;
str.split(' ').forEach(function(s){
  if(s.indexOf('img') > -1) {
    url = s.split("=")[1]
  }
})
// url now contains your url
console.log(url);

Or as a one liner:

var url = str.split(' ').filter(function(s){ return s.indexOf('img') > -1})[0].split("=")[1]
cl3m
  • 2,791
  • 19
  • 21
0

Your best bet is a Regular Expression.

var regEx= /"http:\/\/.+?"/g; //If you want to extract all urls.
var imgEx= /img=".+?"/g // If you want to extract all img parameters.
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
GMchris
  • 5,439
  • 4
  • 22
  • 40