在javascript中将纯文本转换为超链接

我有一个用例,我需要识别字符串中的电话号码并将它们转换为可点击的链接。目前使用外部库超出了范围。


这是我到目前为止所做的:


字符串:“这是我的电话号码 - 1234567890” 我可以使用正则表达式提取 1234567890 作为电话号码。


我现在想在原始字符串中替换它,所以这就是我所做的:


const string = "This is my phone number - 1234567890"

const number = "1234567890"

const newString = '<a href="#">' + number + '</a>'

number = number.replace(number, newString);

当我这样做时,我的输出不是将电话号码作为超链接,而是这样的:


This is my phone number - <a href="#">1234567890</a>

如果我创建没有引号的 newString,就像这样


const newString = <a href="#">number</a>

我的输出是这样的:


This is my phone number - [object Object]

我如何使它成为可点击的链接?


千万里不及你
浏览 944回答 3
3回答

慕森卡

您需要将电话号码替换为链接,然后用于dangerouslySetInnerHTML添加到 React 组件。注意:dangerouslySetInnerHTML之所以调用它,是因为您容易受到来自用户生成内容的 XSS 攻击。您应该先对琴弦进行消毒。const Linkify = ({ text, pattern, formatter }) => {&nbsp; const __html = text.replace(pattern, formatter);&nbsp; return <div dangerouslySetInnerHTML={{ __html }} />;};const text = 'This is my phone number - 1234567890';const pattern = /\d+/g;const formatter = str => `<a href="#${str}">${str}</a>`;ReactDOM.render(&nbsp; <Linkify text={text} pattern={pattern} formatter={formatter} />,&nbsp; root);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="root"></div>不使用dangerouslySetInnerHTML主要问题是将字符串分解为链接/非链接字符串。这可以通过使用此答案中的代码来完成。我更新了代码以将字符串标记为匹配项,因此您可以相应地设置它们的格式。const Linkify = ({ text, pattern, formatter }) => {&nbsp; const arr = getSegments(pattern, text);&nbsp; return arr.map(formatter);};const text = 'This is my phone number - 1234567890, and his is 34234123142';const pattern = /\d+/g;const formatter = ({ text, match }) => match ? <a href={`#${text}`}>{text}</a> : text;ReactDOM.render(&nbsp; <Linkify text={text} pattern={pattern} formatter={formatter} />,&nbsp; root);function getSegments(rex, str) {&nbsp; const segments = [];&nbsp; let lastIndex = 0;&nbsp; let match;&nbsp; rex.lastIndex = 0; // In case there's a dangling previous search&nbsp; while (match = rex.exec(str)) {&nbsp; &nbsp; if (match.index > lastIndex) {&nbsp; &nbsp; &nbsp; segments.push({ text: str.substring(lastIndex, match.index) });&nbsp; &nbsp; }&nbsp; &nbsp; segments.push({ text: match[0], match: true });&nbsp; &nbsp; lastIndex = match.index + match[0].length;&nbsp; }&nbsp; if (lastIndex < str.length) {&nbsp; &nbsp; segments.push({ text: str.substring(lastIndex) });&nbsp; }&nbsp; return segments;}<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="root"></div>

红颜莎娜

您真的不想将“字符串”设置为const newString,我会称其为元素。你可以这样做:const phoneEl = (&nbsp; <a href="#">&nbsp; &nbsp; {number}&nbsp; </a>);哪里number是存储在一个名为变量的电话号码number。然后你会写:<p>My phone number is - {phoneEl}</p>我也建议<href={`tel:${number}`}>如果您希望人们能够单击链接并拨号。

慕桂英4014372

const string = document.querySelector("body");const text = string.innerText;const textArr = text.split(" ").map(item => {&nbsp; if(item.match(/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im)){&nbsp; &nbsp; item = `<a href="tel:${item}">${item}</a>`;&nbsp; }&nbsp; return item;});const newText = textArr.join(" ");console.log({ newText })string.innerHtml = newText;<p class="body">&nbsp; This is my phone number - 555-555-5555</p>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript