简体   繁体   中英

regex replace characters with html tag in string

I'm getting with regex words I need to replace with input tag. But when I'm adding html , it reads as plain string.
Here is my string: "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back". Where i'm doing mistake?

editModalText() {
  const { modalMessage } = this.state
  let regex = /\/#(.*?)#\//g
  let replaced = modalMessage.replace(regex, '<input type="text">')
  return replaced
}

<div>{this.editModalText()}</div>

This is because it is a plain string.

You're going to have to change your approach entirely if you want to mix JSX syntax into your template.

For example, build a tokenizer that would convert your string into an array like:

[
    "Hello, my name is ",
    "/# Ann #/",
    ". I'm working for ",
    "/# IStaff #/",
    ", could you please call me back"
]

Then loop over it and push either the raw string or an appropriate JSX element into a new array, and finally return that.

You can match the middle part by using .*? .

 let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"; let regex = /\\/#(.*?)#\\//g; let replaced = modalMessage.replace(regex, "<input />"); console.log(replaced); 

Also you need to escape your / in the regex with a backslash (\\).
A valid expression starts and ends with / :

/<regex>/<flags>

So in your example:

/          // <- Start of Regular expression
  \/       // <- Match /
  #        // <- Match #
    (.*?)  // <- Match the middle part (non-greedy)
  #        // <- Match #
  \/       // <- Match /
/g         // <- End regex and set "global" flag

Example with HTML:

 let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"; let regex = /\\/#(.*?)#\\//g; let replaced = modalMessage.replace(regex, '<input type="text">'); document.write(replaced); 

You aren't catching the / around the placeholders (/ being a regex special character that needs to be escaped)

using (.+) or (.*) will provide a greedy match. It means, it will match as much as possible, that's why you are matching too much. You want to use a lazy match (the opposite of greedy, that stops as soon as possible), (.+?) or (.*?)

You can use this one :

 let modalMessage = "Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back" let regex = /\\/#(.*?)#\\//g let replaced = modalMessage.replace(regex, '<Input />') console.log(replaced) 

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