【问题标题】:Converting text with <strong></strong> tags into actual bold text?将带有 <strong></strong> 标签的文本转换为实际的粗体文本?
【发布时间】:2021-09-29 19:43:08
【问题描述】:

我有一些来自后端的传入文本,其中包含文本中的 标记以指示粗体。由于它是动态文本,因此我需要捕获标签的任何实例并转换为实际的粗体呈现。我认为正则表达式是答案,但不确定配置。它需要应用粗体并去除标签。

This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>

上下文是一个反应原生应用程序。

【问题讨论】:

  • 你能添加一个 CSS 选择器使它变粗吗?

标签: javascript regex replace tags strip


【解决方案1】:

const text = "This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>.Here is another phone number <strong>888-888-8888</strong>";
const textDiv = document.getElementById('text');
const textSegments = text.split(/(<strong>.*?<\/strong>)/);

textSegments.forEach(textSegment => {
if (textSegment.includes('strong')) {
const span = document.createElement('strong');
span.appendChild(document.createTextNode(textSegment.replace('<strong>','').replace('</strong>', '')));
textDiv.appendChild(span);
} else {
const text = document.createTextNode(textSegment);
textDiv.appendChild(text);
}
})
&lt;div id="text"&gt;&lt;/div&gt;

如果它在 react 应用程序的上下文中,那么它就更简单了。你会做这样的事情。

const text = "This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>.Here is another phone number <strong>888-888-8888</strong>";

const textSegments = text.split(/(<strong>.*?<\/strong>)/);

然后在 JSX 部分中是这样的:

<div>{textSegments.map(segment => {
if (segment.includes('strong')) {
const text = segment.replace('<strong>','').replace('</strong>', '');
return <strong>{text}</strong>;
} else {
return segment;
}
})}</div>

这样的事情应该可以工作。

【讨论】:

  • 这将在 React 应用程序的上下文中,因此无法直接访问 DOM(实际上)。
  • 请查看我的编辑。
【解决方案2】:

如果你想用强标签替换标签,你可以这样做:

var text = 'This <div>is a message that has a phone number that needs to be bold</div>. Please call: <strong>888-888-8888</strong>'

text.replace('div>', 'strong>');

【讨论】:

    【解决方案3】:

    我认为你可以继续使用包含标签的文本

    document.getElementById("dynamictext").innerHTML = "This is a message that has a phone number that needs to be bold. Please call: &lt;strong&gt;888-888-8888&lt;/strong&gt;";
    &lt;div id="dynamictext"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多