Javascript regex help not match char
I'm making my own markdown editor, and it does bold and italic much like stack overflow:
// **bold**
Text = Text.replace(new RegExp("\\*\\*(.+?)\\*\\*", "g"), '<strong>$1</strong>');
// *italic*
Text = Text.replace(new RegExp("\\*(.+?)\\*", "g"), '<em>$1</em>');
The problem is now that if someone want to have a series of asterix in their text like:
开发者_如何学PythonIf you want to do A * B * C then...
This would come out as:
A B C
Stackoverflow does it well where the asterix only work if they are not touching a space character afterwards. Eg:
** Bold ** = not bold
**Bold** = bolded
* Italic * = not italic
*Italic* = italics
So I try to add in [^ ]
to make it match a non space character which is a bit buggy:
// **bold**
Text = Text.replace(new RegExp("\\*\\*(.+?)\\*\\*", "g"), '<strong>$1</strong>');
// *italic*
Text = Text.replace(new RegExp("\\*[^ ](.+?)[^ ]\\*", "g"), '<em>$1</em>');
This seems to strip a character off the start and end of $1 but apart from that it works. How can I modify my regex so both bold and italic are only activated if the text contained within is not padded by any spaces?
Edit
// **bold**
Text = Text.replace(new RegExp("\\*\\*([^ ](.+?)[^ ])\\*\\*", "g"), '<strong>$1</strong>');
// *italic*
Text = Text.replace(new RegExp("\\*([^ ](.+?)[^ ])\\*", "g"), '<em>$1</em>');
But the test case:
this ** shouldnt be bold ** ewfwef
Renders as
this * shouldnt be bold * ewfwef
Put the character classes inside the capture group:
([^ ].+?[^ ])
or a bit shorter (and considers all white spaces):
(\S.+?\S)
精彩评论