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?

1
  • You should have tagged your question with regex. That would help you to do that. Commented Mar 6, 2016 at 16:01

3 Answers 3

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/.

Sign up to request clarification or add additional context in comments.

Comments

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]

3 Comments

Nope, that'd give him "the url". ;)
It's not giving you the pure URL. It's enclosed by ". You just split by = but don't remove the ".
Oh, I see! Sorry :S Just add a .replace('"','') then ;)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.