开发者

Replacing inner text with javascript and regular expression

开发者 https://www.devze.com 2023-03-18 03:41 出处:网络
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...

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

精彩评论

暂无评论...
验证码 换一张
取 消