1

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.