1. 程式人生 > 其它 >將富文字內容區分圖片和文字

將富文字內容區分圖片和文字

摘要

在一些快應用中,比如小程式中,可能會有需求,在輸出的文章中,需要對圖片可預覽,正常的富文字內容是<img/>標籤,無法預覽處理,因此需要將富文字中的圖片路徑和文字區分開發,以實現圖片預覽效果

程式碼

/* 對富文字進行分割 */
	
	function sliceStr(str) {
		let result = [];
		// 提取url的正則
		const reg = /<img.+?src=[\"\'](.+?)[\"\'].{0,}?>/g;
		let index = 0;
		
		// 針對p標籤處理(瀏覽器端可能會有間隔,導致顯示不一致)
		// 加上類名,可以在css中處理
str = str.replace(/<p/g, '<p data-type="nodeText"') str.replace(reg, (value, word, position) => { const valueLen = value.length; const text = { type: 'text', content: str.slice(index, position) } const img = { type: 'image', content: word } result.
push(text, img); index = position + valueLen; }) result.push({ type: 'text', content: str.slice(index) }) return result }

最終的結果是這種結構

const testStr=`<p>可靠訊息,喪屍來襲</p>↵<p></p>↵<img src="http://test2.img.hiwemeet.com/pic/750-1624-607c0816fc41244429df1b658d4b22c7/0" alt="undefined" style="float:none;height: auto;width: auto"/>↵<p>大家快跑啊</p>`
console.log(trans(testStr))

在這裡插入圖片描述

原理

主要是利用了string的replace方法,第二個引數可以傳遞一個函式
在這裡插入圖片描述
函式的引數有

1.第一個引數是匹配到的字串 如上就是

<img src="http://test2.img.hiwemeet.com/pic/750-1624-607c0816fc41244429df1b658d4b22c7/0" alt="undefined" style="float:none;height: auto;width: auto"/>

2.第二個引數是子表示式匹配的字串 何謂子表示式?就是正則中括號中代表的內容,如果有多個括號的子表示式,那麼這個引數可能有多個,這部分匹配到的內容就是對應的img中的src

http://test2.img.hiwemeet.com/pic/750-1624-607c0816fc41244429df1b658d4b22c7/0

3.第三個引數匹配到的字串出現的位置,字串的開始對應的index
4.第四個引數原始的字串