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?

Sergino
  • 10,128
  • 30
  • 98
  • 159
  • Probably `string.match(/bodypart_[^\/]+/i)` will do. If no match is found, it returns *null*, otherwise an array of the first match. – RobG Apr 02 '15 at 02:55

3 Answers3

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>
Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52
  • getting error here: `img.src.match(/BodyPart[^\/]*/)` saying `img.src` underfined. I cehcked on debugger `img` has outerHTML `outerHTML: " – Sergino Apr 02 '15 at 04:01
  • was trying `$(img)attr("src")` - not avaliable – Sergino Apr 02 '15 at 04:03
  • 1
    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. – Gaël Barbin Apr 02 '15 at 07:11
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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
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">
guest271314
  • 1
  • 15
  • 104
  • 177