简体   繁体   中英

Regex, match everything, except double asterisks

I am creating a text editor interface where the user is able to format the text, and he can see the modifications in a div next to it.

To highlight a bunch of text, I reserved double asterisks as the following ** text **, just like here in stackoverflow.

My code looks like the following:

replace(/\*{2}([^\*]*)\*{2}/g, "<strong>$1</strong>")

but my problem is, if the text is including an asterisk, the following output can be seen:

** text* **,

and not text*

how is it possible to negate double characters for matching to not break the HTML tag in the output?

You can deal with single asterisks followed by at least one other character just adding (?:\\*[^*]+)* :

yourstr = yourstr.replace(/\*\*([^*]*(?:\*[^*]+)*)\*\*/g, "<strong>$1</strong>");

Note that escaping * in a character class is useless, and writing \\*{2} is longer than \\*\\* .

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