简体   繁体   中英

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

I create a javascript parser for my markup language. I wish no spaces between tags and content like this:

__underline a sentence __and more. 
(or correctly : __underline a sentence__ and more.)

to :

<u>underline a sentence</u> and more.

But result is in the first case :

<u>underline a sentence </u>and more.

My code :

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+'>');
}

Thanks.

Use the below regex and then replace the matched characters with <u>$1</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>$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.'
__(.*?)[ ]*__[ ]*

Try this.Replace by <u>$1</u> .See demo.

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);

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