简体   繁体   中英

Make regex find a text inside tags with line breaks in the content - JavaScript

thanks for coming here, so i've got this little code:

while(/\[del\](.*?)\[\/del\]/i.exec(text) != null)
text = text.replace(/\[del\](.*?)\[\/del\]/i, "<s>$1</s>");

but when there are line breaks, it wont match. Example:

[del]asdsadasda
asdadsadsadsadasdsadsa[/del] - this won't be matched

I'm really new to regex, so what I'm doing wrong?

By default in many regex flavors, the dot doesn't match the newline character. Javascript doesn't have the singleline modifier (?s) to change this behaviour. The most current trick to match all characters including newlines is to use [\\s\\S] that matches all that is a whitespace character and all that is not a whitespace character .

As an aside comment, you don't need to put the replace method in a while loop, since the replace will only perform a replacement if something is found. If you want to replace all occurences, just add the g command at the end of the pattern.

text = text.replace(/\[del\]([\s\S]*?)\[\/del\]/ig, "<s>$1</s>");

Note that for this specific replacement, since your del tag doesn't seem to have parameters, you can simply write:

text = text.replace(/\[(\/?)del\]/ig, "<$1s>");

(it avoids a lot of work)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM