Tengo este texto en cadena:
let text = "#Jim, Start editing to see some magic happen!";¿Cómo puedo querer llegar?
text = "<span style="color:red">#Jim</span>, Start editing to see some magic happen!";mi intento fallido de la siguiente manera:
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
No estoy seguro de que esto sea lo que realmente necesitas. De todos modos, creo que es un paso más cerca.
Hice una nueva expresión regular para obtener '#' + palabras y para que el texto se actualice con replace es necesario jugar
text = textDespués:
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> ); }Su enfoque funciona, es solo que el estilo no se representa en innerHTML
Ejecute este ejemplo y verá que el hashtag aparece en negrita (también cambió un poco su expresión regular)
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>`; });Si desea que se apliquen los estilos, debe cambiar la Encapsulación en su componente a Ninguno así:
@Component({ selector: 'app-my-hashtag-component', styles: ['./app-my-hashtag-component.css'], templateUrl: './app-my-hashtag-component.html', encapsulation: ViewEncapsulation.None, })