简体   繁体   中英

Remove HTML Tags and whitespace from string using regex javascript

I have string like this:

<p>Dignissimos quo nostrum enim quo necessitatibus consequatur sed voluptatem. Provident aut dolorum voluptas qui. Veniam molestiae perspiciatis aspernatur quod. Labore maxime ipsa ab nesciunt. Dignissimos quo nostrum enim quo necessitatibus consequatur sed voluptatem. Provident aut dolorum voluptas qui. Veniam molestiae perspiciatis aspernatur quod. Labore maxime ipsa ab nesciunt.</p>
<p>Dignissimos quo nostrum enim quo necessitatibus consequatur sed voluptatem. Provident aut dolorum voluptas qui. Veniam molestiae perspiciatis aspernatur quod. Labore maxime ipsa ab nesciunt. Dignissimos quo nostrum enim quo necessitatibus consequatur sed voluptatem. Provident aut dolorum voluptas qui. Veniam molestiae perspiciatis aspernatur quod. Labore maxime ipsa ab nesciunt.</p>

I want to remove the HTML Tags and whitespace using regex then get the length.

I have already tried this:

this.text.replace(/(<([^>]+)>)/ig, ''); //This is just remove the HTML Tags

and this remove the whitespace:

this.text.replace(/\s/g, "")

I don't know how to combine the regex to remove the HTML tags and whitespace :(

function clearTags(html) {
    var div = document.createElement("div");
    div.innerHTML = html;
    var text = div.textContent || div.innerText || "";
    return text.replace(/\s+/g, '');
}

This appears to work.

<[\/a-z]+>|\s

For regex texting, I use https://regex101.com/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM