Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
replace string text with html tag using regex

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>
    );
}
about 4 years ago · Juan Pablo Isaza Report

0

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,
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!