Dart – Replacing regex match in the middle of String

I’m trying to remove all links from a html string and to do so I’m using a regex to replace all <a> tags by <p>. The regex works fine when the tag is isolated, but in the middle of the string, it doesn’t work.

String tag = '<a href=\"https://www.google.com/\" target=\"_blank\" rel=\"noopener\">word</a>';
String html = 'regex with a <a href=\"https://www.google.com/\" target=\"_blank\" rel=\"noopener\">word</a> in the middle';

const regexString = r'^<a href=[a-zA-Z0-9_\W]([^>]*)';
final regex = RegExp(regexString);

html = html.replaceAll(regex, '<p').replaceAll('</a>', '</p>');
tag = tag.replaceAll(regex, '<p').replaceAll('</a>', '</p>');
print(tag); //<p>word</p>
print(html); //regex with a <a href="https://www.google.com/" target="_blank" rel="noopener">word</p> in the middle

I’m expecting the result of print(html) to be the same as print(tag)

>Solution :

Change your regex to this:

const regexString = r'<a href=[a-zA-Z0-9_\W]([^>]*)';

^ at the start of your regex make it to check only start of string.

for replacing <a> with " " you can try this:

const regexString = r'<a href=[a-zA-Z0-9_\W]([^>]*)>';

Leave a Reply