简体   繁体   中英

Remove all symbols, html and special chars from string

How can I remove all elements from a string apart from raw text and a single space? However, certain symbols are not getting removed, - , –, ’

Currently I use:

let descriptionString = description.replace(/(<([^>]+)>)/gi, "").replace(/[^a-zA-Z 0-9]+/g,"");

description is a field from wordpress which can contain anything, html, symbols, encoded chars etc.

Example content is:

Surgical Sim 8211 Kate O8217Connor Sim Lab I need to remove 8217 - its only removed the hash at the moment.

I need to display the result in a react-native View . I don't want to use a WebView to render html .

Any ideas?

Check the below function. It removes all the special charactors, html and symbols.

function filterString(html)
    {
       var tmp = document.createElement("DIV");
       tmp.innerHTML = html;
       tmp = tmp.textContent || tmp.innerText || "";

       tmp =tmp.replace(/([,"'0-9\-.~!@#$%^&*()_+=–’`{}\[\]\|\\:;"<>\/?])+/g, '').replace(/^(-)+|(-)+$/g,'');
       return tmp;
    }

    console.log(filterString("<html>asdasjhd<body>%dasd test - , ' &#8211;, &#8217; ytest jsdnja  @!@#@&^$@$ &nbsp;"));

Also you can test it for your string

console.log(filterString("Surgical Sim 8211 Kate O8217Connor  Sim Lab"));

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