Refactoring starting place for regex

Viewed 93

I have a function that stripes HTML markup to display inside of a text element.

stripChar: function stripChar(string) {
  string = string.replace(/<\/?[^>]+(>|$)/g, "")
  string = string.trim()
  string = string.replace(/(\n{2,})/gm,"\n\n");
  string = string.replace(/&hellip;/g,"...")
  string = string.replace(/&nbsp;/g,"")
  let changeencode = entities.decode(string);
  return changeencode;
}

This has worked great for me, but I have a new requirement and Im struggle to work out where I should start refactoring the code above. I still need to stripe out the above, but I have 2 exceptions;

  • List items, <ul><li>, I need to handle these so that they still appear as a bullet point
  • Hyperlinks, I want to use the react-native-hyperlink, so I need to leave intack the <a> for me to handle separately

Whilst the function is great for generalise tag replacement, its less flexible for my needs above.

1 Answers

You may use

stripChar: function stripChar(string) {
  string = string.replace(/&nbsp;|<(?!\/?(?:li|ul|a)\b)\/?[^>]+(?:>|$)/g, "");
  string = string.trim();
  string = string.replace(/\n{2,}/g,"\n\n");
  string = string.replace(/&hellip;/g,"...")
  let changeencode = entities.decode(string);
  return changeencode;
}

The main changes:

  • .replace(/&nbsp;/g,"") is moved to the first replace
  • The first replace is now used with a new regex pattern where the li, ul and a tags are excluded from the matches using a negative lookahead (?!\/?(?:li|ul|a)\b).

See the updated regex demo here.

Related