简体   繁体   中英

How can I remove HTML markup from strings in state data?

  1. I fetch data from an API using 'axios'.
  2. I save the data recieved in my State.
  3. I output the information given from the state in a table.

The issue is that the Strings I recieve from the fetched data include a lot of HTML tags such as < p > , < h1 > & < br > I would like to remove these if possible.

Note that I do not use JQuery

state = {
  companyName: "Loading",
      loading: true,
         data: [] //THIS IS WHERE I STORE ALL THE DATA THAT I FETCH
}
data(props) {
  return(
    <div>
      <Table celled>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell>Index</Table.HeaderCell>
            <Table.HeaderCell>Författning</Table.HeaderCell>

          </Table.Row>
        </Table.Header>

        {props.map((lawList, index) => (
                    <Table.Body>
                      <Table.Row>
                        <Table.Cell>{index + 1}</Table.Cell>
/* The line below displays the data, but the data includes alot of html tags that i wish to have removed */
                        <Table.Cell>{lawList.lawDTO.name}</Table.Cell>
                      </Table.Row>
                    </Table.Body>
            ))}
      </Table>
    </div>
  )
}
render() {
    return(
        <div>
                <h3> {this.data(this.state.data)} </h3>

        </div>   
     )}
   }

You can use a regular expression:

 const test = '<br>asdasd</br><p>test</p>'.replace(/<.{1,2}>|<.{2,3}>/g, ''); console.log(test); 

You could do something like this, as soon aj you have read your data:

 let data = "<p>first <h1> second <br> third </p>"; data = data.replace(/<\\/?[^>]+(>|$)/g, ''); console.log(data); 

Possibly, you want to render the html ?

render() {
  return (
    <div dangerouslySetInnerHTML={{ __html: this.state.data }}></div>
  )
}

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