1

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

2 Answers 2

1

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>
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice, I know what's missing now! tq Luis!
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,
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.