Rich Text to Simple Text

Is there a way to get Rich Text into simple plain text format?

Yup! You can use regular expressions and the JavaScript replace function to get rid of the html tags!

Here is an example of how I did it…

//regular expression to remove the script/html  tags
var regex = /(<([^>]+)>)/ig;

//regex to remove the &rsquo; special character with '
var specialRegex = /(&rsquo;)/ig;

//This will replace all tags with an empty string.
let plainText = richText.replace(regex, "");

//this will replace left over &rsquo; with a '
plainText = plainText.replace(specialRegex, "'");

Now we can also do this in less lines of code by combining lines.

//regular expression to remove the script/html  tags 
var regex = /(<([^>]+)>)/ig;  

//regex to remove the &rsquo; special character with ' 
var specialRegex = /(&rsquo;)/ig;  

//This will replace all tags with an empty string and replace &rsquo; with a '
let plainText = richText.replace(regex, "").replace(specialRegex, "'"); 

We can even do it in one line of code! It just can become difficult to read. The answer above is my preferred way to do it.

let plainText = richText.replace(/(<([^>]+)>)/ig, "").replace(/(&rsquo;)/ig, "'"); 

Let me know if this helped you!

#regex #regularExpressions