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
  • 953
  • 13
  • 24

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
  • 322,446
  • 66
  • 504
  • 612
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,761
  • 17
  • 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
  • 64,912
  • 15
  • 96
  • 124
GMchris
  • 4,979
  • 4
  • 21
  • 38