1

I have an element on the form:

<img src="/media/BodyPart_7d0cf57e-a461-44fd-903f-ce77b005e299/300/0" class="media-item">

I want to extract the Bodypart_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Here ix the mask of the string "/{anyt-ext-here}/BodyPart_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/{any-number-here}/{any-number-here}"

What is the best day of doint it?

1
  • Probably string.match(/bodypart_[^\/]+/i) will do. If no match is found, it returns null, otherwise an array of the first match. Commented Apr 2, 2015 at 2:55

3 Answers 3

1

Something like that:

var output= document.querySelector("#output");
var img= document.querySelector(".media-item"); //assuming there is only the wanted img of this class

var extracted_string= img.src.match(/BodyPart[^\/]*/);
if( extracted_string )
  output.innerHTML= extracted_string;
else
  output.innerHTML= "no match found";
      
<img src="/media/BodyPart_7d0cf57e-a461-44fd-903f-ce77b005e299/300/0" class="media-item">

<div id="output"></div>

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

3 Comments

getting error here: img.src.match(/BodyPart[^\/]*/) saying img.src underfined. I cehcked on debugger img has outerHTML outerHTML: "<img src="/media/BodyPart_......." I actually used jquery $(this).prev("img.media-item"); insteard of document.querySelector probably that is the reason why src in uderfined
was trying $(img)attr("src") - not avaliable
jquery returns an array of all element matching the selector, even if there is only one returned. So you can use: $(this).prev("img.media-item")[0] to get the img element, then you will be able to get the src attribute with: $(this).prev("img.media-item")[0].src, and $(this).prev("img.media-item")[0].src.match(/BodyPart[^\/]*/) to get the URL part requested.
1

Try utilizing .split() , .filter()

var img = document.querySelectorAll("img[src*=BodyPart]")[0];
var res = img.src.split("/").filter(function(src, i) {
            return /BodyPart/.test(src)
          })[0];
console.log(res);
<img src="/media/BodyPart_7d0cf57e-a461-44fd-903f-ce77b005e299/300/0" class="media-item">

Comments

1

Try this code:

var input   = "<img src=\"/media/BodyPart_7d0cf57e-a461-44fd-903f-ce77b005e299/300/0\" class=\"media-item\">";
var matches = input.match(/^<img src=.*\/(BodyPart\_\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12})\//);

alert(matches[1]);

Output:

BodyPart_7d0cf57e-a461-44fd-903f-ce77b005e299

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.