JS批量替換img標籤為對應img標籤中的某個attr屬性的值
阿新 • • 發佈:2018-11-12
【需求】: 如下圖,頁面展示的表情和文字,現在在點選“傳送”按鈕時,需要將img標籤替換成相應的【文字】:
【解決】:
具體實現如下:
要替換的字串為:
html == <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" text_web="微笑" class="qqemoji qqemoji0">我愛你<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" text_web="快哭了" class="qqemoji qqemoji50">哈哈
將img標籤替換成其中的text_web的值:
sendMsg1() { let $myInput = this.$el.querySelector('.my-input'), attrReg = /text_web=[\'\"]?([^\'\"]*)[\'\"]?/i, html = $myInput.innerHTML, Content = ''; console.log('html == ', html) Content = html.replace(/<img(?:.|\s)*?>/gi, function (item) { return '[' + item.match(attrReg)[1] + ']' }) console.log('Content : ', Content) },
列印結果如下: