我为我的标记语言创建了一个javascript解析器。 我希望标签和内容之间没有这样的空格:
__underline a sentence __and more.
(or correctly : __underline a sentence__ and more.)
到:
<u>underline a sentence</u> and more.
但结果是第一种情况:
<u>underline a sentence </u>and more.
我的代码:
var tabML = ['\'','*','_'],
tabHTML = ['em','strong','u']
tag, char;
for(var i=0; i<tabML.length; i++){
tag = tabHTML[i]; char = tabML[i];
regex = new RegExp(char+char+'(.+)'+char+char, 'ig');
txt = txt.replace(regex, '<'+tag+'>$1</'+tag+'>');
}
感谢。
答案 0 :(得分:0)
使用以下正则表达式,然后将匹配的字符替换为<u>$1</u>
__\s*(.*?)\s*__\s*
> var s1 = "__underline a sentence __and more."
undefined
> var s2 = "__underline a sentence__ and more."
undefined
> s1.replace(/__\s*(.*?)\s*__\s*/g, '<u>$1</u> ')
'<u>underline a sentence</u> and more.'
> s2.replace(/__\s*(.*?)\s*__\s*/g, '<u>$1</u> ')
'<u>underline a sentence</u> and more.'
答案 1 :(得分:0)
__(.*?)[ ]*__[ ]*
试试这个。<u>$1</u>
。见。演示。
https://regex101.com/r/tX2bH4/5
var re = /__(.*?)[ ]*__[ ]*/gm;
var str = '__underline a sentence __and more.\n__underline a sentence__ and more.';
var subst = '<u>$1</u> ';
var result = str.replace(re, subst);