简体   繁体   中英

Performance issue using regex to replace/clear substring

I have a string containing things like this:

<a@{style}@{class}@{data} id="@{attr:id}">@{child:content} @{child:whatever}</a>

Everything to do here is just clear @{xxx} , except sub-strings starting with @{child: .

I used str.match() to get all sub-strings "@{*}" in an array to search and keep all @{child: substrings:

var matches = str.match(new RegExp("@\{(.*?)\}",'g'));
if (matches && matches.length){
    for(var i=0; i<matches.length; i++){
        if (matches[i].search("@{child:") == -1) str = str.replace(matches[i],'');  
    }
}

I got it running ok, but it's too slow when string becomes bigger (~2 seconds / +1000 nodes like this one on top)

Is there some alternative to do it, maybe using a rule (if exists) to escape @{child: direct in regex and improve performance?

If I understand your question correctly you don't want to remove the @{child:...} sub-strings but everything else of the format @{...} should go. In which case can you could change the regular expression to check that child: is not matched when you perform the replace:

var str = '<a@{style}@{class}@{data} id="@{attr:id}">@{child:content} @{child:whatever}</a>';
str = str.replace(/@\{((?!child:)[\s\S])+?\}/g, '');

This seems pretty fast.

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