Skip to content

Instantly share code, notes, and snippets.

@tuantvk
Created December 17, 2020 02:05
Show Gist options
  • Save tuantvk/36a315da30830c445d01d6e1fbb65aa7 to your computer and use it in GitHub Desktop.
Save tuantvk/36a315da30830c445d01d6e1fbb65aa7 to your computer and use it in GitHub Desktop.
Strip HTML tags from string in JavaScript
function cleanTagHtml(str) {
if (str && str.trim().length) {
let data = [];
let arr = str
.replace(/<\/?[^>]+(>|$)/g, "")
.split("&nbsp;");
// break one line when multiple &nbsp;
for (let i = 0; i < arr.length; i++) {
if (arr[i] && arr[i].trim()) {
data.push(arr[i]);
} else if (arr[i - 1] && arr[i - 1].trim()) {
data.push("\n");
}
}
return data.join("");
}
return "";
}
@onigetoc
Copy link

Hi, It do not strip <a href tags

@tuantvk
Copy link
Author

tuantvk commented Mar 14, 2024

@onigetoc I checked it was still working. Can you give me your example?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment