假設我有這個字串:
<img class="emoji emoji-small" src="./img-apple-64/1f525.png" alt="??">This is only<img class="emoji emoji-small" src="./img-apple-64/1f525.png" alt="??"> <img src="./img-apple-64/1f916.png" alt="如何僅從字串中獲取文本,而忽略標簽">what i want<img src="./img-apple-64/1f916.png" alt="如何僅從字串中獲取文本,而忽略標簽">
我只需要提取沒有<img標簽的文本部分。在上面的例子中,這是我需要的結果:
This is only what i want
有沒有一種快速/簡單的方法來做到這一點,而不必回圈整個字串并手動替換東西?
uj5u.com熱心網友回復:
使用 DOM?
const str = `<img src="./img-apple-64/1f525.png" alt="如何僅從字串中獲取文本,而忽略標簽">This is only<img src="./img-apple-64/1f525.png" alt="如何僅從字串中獲取文本,而忽略標簽"> <img src="./img-apple-64/1f916.png" alt="如何僅從字串中獲取文本,而忽略標簽">what i want<img src="./img-apple-64/1f916.png" alt="如何僅從字串中獲取文本,而忽略標簽">`
const div = document.createElement("div");
div.innerHTML = str
console.log(div.textContent)
uj5u.com熱心網友回復:
以下正則運算式:
/(?<=\>)([^\<][\s\w]{1,})/gm
會為你做這件事。見下文:
let str = '<img src="./img-apple-64/1f525.png" alt="如何僅從字串中獲取文本,而忽略標簽">This is only<img src="./img-apple-64/1f525.png" alt="如何僅從字串中獲取文本,而忽略標簽"> <img src="./img-apple-64/1f916.png" alt="如何僅從字串中獲取文本,而忽略標簽">what i want<img src="./img-apple-64/1f916.png" alt="如何僅從字串中獲取文本,而忽略標簽">'
let match = str.match(/(?<=\>)([^\<][\s\w]{1,})/gm);
match 是一個包含值的陣列 ['This is only', 'what I want']
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/383574.html
標籤:javascript
