Search code examples
regexreplacedartreplaceall

replaceAllMapped matches with span elements


I want to replace all matched strings after regExp with same strings in span elements. Is this possible? I want to do something like that: final text = message.replaceAllMapped(exp, (match) => '<span>exp, (match)</span>');


Solution

  • You may use String#replaceAllMapped like this:

    final exp = new RegExp(r'\d+(?:\.\d+)?'); 
    String message = 'test 40.40 test 20.20'; 
    final text = message.replaceAllMapped(exp, 
            (Match m) => "<span>${m[0]}</span>");
    print(text);
    

    Output: test <span>40.40</span> test <span>20.20</span>

    Here, m is the Match object that the regex engine finds and passes to the arrow method where the first item in the m array is inserted in between <span> and </span> inside an interpolated double quoted string literal.