简体   繁体   中英

React javascript check if string contains specific word and add something like link react router / styles to specific word

is there any solution how to check strings(ex:Google) and add Link react router into specific word(ex:Google)?

example like this photo

before

前

after

后

this is my very simple code

import React, { Component } from "react";
import { Link } from "react-router-dom";

class App extends Component {
  state = {
    text: "Google is my Friend, Google is Search Engine, Thanks to google"
    website: "Google Friend"
  };

  render() {
    let text = null;
    if (this.state.text.includes(this.state.website)) {
      return (text = (
        <div>
          <Link to={"/example"}>Google </Link> then state text
        </div>
      ));
    }
    return <div>{text}</div>;
  }
}

export default App;

it would be more helpful if you can show me how to add style inside specific word(ex: Google) like changing color, or adding bold/italic or anything

thanks

You can do it like this:

{this.state.text.split(" ").map(text => {
   return text === "Google" ? <Link to="/google">Google</Link> : text;
})}

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