简体   繁体   中英

Replacing inner text with javascript and regular expression

I am trying to do a modify a text which contain some special tags. I believe it should be possible by a single regular expression, but am stuck...

What I want to do is easier to explain by an example:

If I have this text:

{Lorem Ipsum} is simply {dummy text} of the printing and typesetting industry.

I want as a result this:

<span>Lorem Ipsum</span> is <span>simply dummy</span> text of the printing and typesetting industry.

I a } is encountered with no previous matching { then it should be ignored.

I know I can match all inner texts with this \{(.*?)\} but am lost on how to proceed, any help would be appriciated.

You are close.

text = text.replace(/{(.*?)}/g, '<span>$1</span>')

should do the trick. The g modifier makes replace to replace every occurrence of the pattern and $1 refers to the content of the first capture group.

Btw. escaping the {} is not necessary here as {(.*?)} is not a special construct. It still might be better to escape them for clarity.

More about regular expression in JavaScript in the MDN documentation .

A better way would be to match \{([^{}]*)\} . This ensures that only innermost pairs of braces are matched; unbalanced matches are impossible this way.

result = subject.replace(/\{([^{}]*)\}/g, "<span>$1</span>");

However, this will have to be applied several times if nested braces are possible. And it doesn't check whether those braces occur in comments, quotes etc., of course.

var str = '{Lorem Ipsum} is simply {dummy text} of the printing and typesetting industry.';
var spanStr = str.replace(/{(.*?)}/g, '<span>$1</span>');

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