Home > OS >  replace string text with html tag using regex
replace string text with html tag using regex

Time:05-27

I've this text in string:

  let text = "#Jim, Start editing to see some magic happen!";

how can I want to make it to?

text = "<span style="color:red">#Jim</span>, Start editing to see some magic happen!";

my failed attempt as below:

export default function App() {
  let text = "#Jim, Start editing to see some magic happen!";

  // const regex = /#|\[|\]/gm;
  // text = text.replace(regex, (innerText) => {
  //   return <span style={{ color: "red" }}>{innerText}</span>;
  // });

  return (
    <div className="App">
      <div
        dangerouslySetInnerHTML={{
          __html: text
        }}
      />
    </div>
  );
}

https://codesandbox.io/s/youthful-gwen-55757z?file=/src/App.js:24-419

CodePudding user response:

I'm not sure this is what you really need. Anyway, I think it's a step closer.

I made a new regex to get '#' words and for the text to be updated with replace it is necessary to play

text = text

Then:

import "./styles.css";

export default function App() {
    let text = "#Jim, Start editing to see some magic happen!";

    const regex = /\#[a-zA-Z] /gm;
    text = text.replace(regex, (match) => {
        return `<span style="color: red">${match}</span>`;
    });
    return (
        <div className="App">
            <div
                dangerouslySetInnerHTML={{
                    __html: text
                }}
            />
        </div>
    );
}

CodePudding user response:

Your approach works, its just that the style is not rendered in innerHTML

Run this example and you'll see that the hashtag appears bold (Also changed your regex a bit)

let text = '#Jim, Start editing to see some magic happen!';

const regex = /(# [a-zA-Z0-9(_)]{1,})/gm;
text = text.replace(regex, (match) => {
  return `<strong>${match}</strong>`;
});

If you want the styles to apply you have to change the Encapsulation in your component to None like so:

@Component({
  selector: 'app-my-hashtag-component',
  styles: ['./app-my-hashtag-component.css'],
  templateUrl: './app-my-hashtag-component.html',
  encapsulation: ViewEncapsulation.None,
})
  • Related