使用javascript解析字符串

时间:2015-04-02 02:48:55

标签: javascript regex

我在表单上有一个元素:

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

我想提取Bodypart_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

这里是字符串"/{anyt-ext-here}/BodyPart_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/{any-number-here}/{any-number-here}"

的掩码

doint最好的一天是什么?

3 个答案:

答案 0 :(得分:1)

类似的东西:

&#13;
&#13;
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";
      
&#13;
<img src="/media/BodyPart_7d0cf57e-a461-44fd-903f-ce77b005e299/300/0" class="media-item">

<div id="output"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这段代码:

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]);

输出:

BodyPart_7d0cf57e-a461-44fd-903f-ce77b005e299

答案 2 :(得分:1)

尝试使用.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">