简体   繁体   中英

Changing the tags with the text between the tags

My title sounds complicated so i'll try to simplify it by making an example

i have these selfmade tags like

{tag}tagtext{tag}

and i'm trying to change this into

<span>same tagtext</span>

i tried using regex but i couldn't really figure out how could i get the text between the tags and then also change the tags to something else.

i got the text between the tags with

string.match('{tag}(.*){tag}');

Also all the tags are same and for some reason the match function gave me only the first result it found. I guess it has something to do with my regex.

Also i do not want to do it with a loop because it will start to work as an live editor and i need to keep the performace fast.

/(\{tag\})(.*?)\1/g
 ^^^^^^^^^  ^^ ^^ ^  
    1        2  3 4
1: Match tag and put in group 1
2: *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
3: matches the same text as most recently matched by the 1st capturing group
4: Global pattern flags, all matches.

 var temp = "{tag}tagtext1{tag}{tag}tagtext2{tag}\\n{tag}tagtext3{tag}{tag}tagtext4{tag}"; console.log(temp.replace(/(\\{tag\\})(.*?)\\1/g,"<span>$2</span>")); 

Is this your expect result ?

<span>tagtext1</span><span>tagtext2</span>
<span>tagtext3</span><span>tagtext4</span>

You have to use the global modifier or g after a RegEx expression in order to enable all matches. What language are you using for RegEx?

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