繁体   English   中英

使用正则表达式将字符串文本替换为 html 标记

[英]replace string text with html tag using regex

我在字符串中有这个文本:

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

我怎么能做到?

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

我的失败尝试如下:

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

我不确定这是你真正需要的。 无论如何,我认为这更近了一步。

我制作了一个新的正则表达式来获取“#”+单词,并且要使用替换来更新文本,有必要玩

text = text

然后:

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>
    );
}

您的方法有效,只是样式未在innerHTML中呈现

运行此示例,您会看到主题标签显示为粗体(还稍微更改了您的正则表达式)

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>`;
});

如果要应用样式,则必须将组件中的封装更改为无,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM