简体   繁体   中英

Javascript replace with reference to matched group on all matches

my sample text is :

'<div class="emoji-icons emoji-smile" e-type="smile" style="display:inline-block;" contenteditable="false"></div> is <div class="emoji-icons emoji-grinning" e-type="grinning" style="display:inline-block;" contenteditable="false"></div> very time.'

replace command is :

text.replace(/<div class="emoji-icons (?:.*)" e-type="([a-z]*)"[^>]+><\/div>/ig, '$1')

i want replace all div tag with e-type attribute value. result must be "smile is grinning vary time."

but this regex not work on all matched and work on last matches.

Any ideas or suggestions?

You need to replace (?:.*)" with (?:.*?)" , also there is no need for () so just use .*?"

 var text = '<div class="emoji-icons emoji-smile" e-type="smile" style="display:inline-block;" contenteditable="false"></div> is <div class="emoji-icons emoji-grinning" e-type="grinning" style="display:inline-block;" contenteditable="false"></div> very time.'; text = text.replace(/<div class="emoji-icons.*?" e-type="([az]*)"[^>]+><\\/div>/ig, '$1') document.write(text);

.*? : Between zero and unlimited times, as few times as possible

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