2016-11-19 92 views
-4

考慮以下串串:查找和包裹包含換行符

You look away whilst I weave needles 
through my skin to seal the scars, 
running repairs, not alterations. 

這實際上是存儲在數據庫爲:

You look away whilst I weave needles\r\n 
through my skin to seal the scars,\r\n 
running repairs, not alterations.\r\n 

我怎麼會發現,敷在最後兩行一個span標籤? e.g

You look away whilst I weave needles 
<span>through my skin to seal the scars, 
running repairs, not alterations.</span> 

目前我有:

let regex = new RegExp(stringToMatch,'m'); //I thought 'm', multiline might work? 
poem = poem.replace(regex, '<span>' + stringToMatch + '</span>') 

的正常工作對於不包含任何\r\n字符串。

回答

0

我建議你使用這樣的

var poem = 'You look away whilst I weave needles\r\nthrough my skin to seal the scars,\r\nrunning repairs, not alterations.\r\n'; 
let regex = /((.+[\r\n]+)+)((.+[\r\n]+){2})/ 
poem = poem.replace(regex, '$1<span>$3</span>');