如何去掉正则表达式开头和结尾的白色space?

how to remove white space at the beginning and end of a regular expression?

我为我的标记语言创建了一个 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+'></'+tag+'>');
}

谢谢。

使用下面的正则表达式,然后将匹配的字符替换为 <u></u>

__\s*(.*?)\s*__\s*

DEMO

> var s1 = "__underline a sentence __and more."
undefined
> var s2 = "__underline a sentence__ and more."
undefined
> s1.replace(/__\s*(.*?)\s*__\s*/g, '<u></u> ')
'<u>underline a sentence</u> and more.'
> s2.replace(/__\s*(.*?)\s*__\s*/g, '<u></u> ')
'<u>underline a sentence</u> and more.'
__(.*?)[ ]*__[ ]*

通过 <u></u> 尝试 this.Replace。查看演示。

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></u> ';

var result = str.replace(re, subst);