如何在alt上更改字符串img的值

时间:2015-10-19 12:34:49

标签: javascript jquery

如何删除img标记并将其替换为alt

的值
var data="how are you <img src='blabla/emot/smile.gif' alt=':)'> yes <img src='blabla/emot/smile.gif' alt=':)'> <img src='blabla/emot/melet.gif' alt=':P'>";

到最终结果

var data="how are you :) yes :) :P";

我想删除img标记,并使用jQuery或javascript

将其替换为alt中的值

1 个答案:

答案 0 :(得分:0)

使用jQuery one-liner非常简单:

var data = "how are you <img src='blabla/emot/smile.gif' alt=':)'> yes <img src='blabla/emot/smile.gif' alt=':)'> <img src='blabla/emot/melet.gif' alt=':P'>";

var result =
    $('<div>').html(data)                 // create `<div>` and put data as contents
              .find('img')                // find `<img>` elements in `<div>`
              .replaceWith(function() {   // replace `<img>` elements
                  return this.alt;        // with their `alt` attributes
              })
              .end()                      // return back to `<div>` element
              .text();                    // get text contents

console.log( result );  // "how are you :) yes :) :P"