JavaScript 将文本中每个匹配项的文本替换为函数结果
我试图用该文本片段的函数结果替换 textarea 元素中的所有链接。
示例:
url = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g; Text = "Text with link inside www.stackoverflow.com"; text.replace(url, convert(RESULT)); document.write(text); function convert(link){ return " XX " + link + "XX"; }
我需要的是在该字符串中找到的每个链接都被转换为由 XX 或任何其他字符串包围。 事实上,我需要将文本中的每个链接发送到该函数,这样我就可以替换它们中的每一个。
我已经在网上搜索了几个小时。尝试了很多东西。什么都不起作用。
关于如何做到这一点有什么想法吗?
提前致谢!
I'm trying to replace all links in a textarea element with the result of a function for that piece of the text.
Example:
url = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g; Text = "Text with link inside www.stackoverflow.com"; text.replace(url, convert(RESULT)); document.write(text); function convert(link){ return " XX " + link + "XX"; }
What I need is that every link found in that string, get converted to be surrounded by XX or any other string.
The fact is that I need EACH link in the text to be sent to that function, so I can replace each of them.
I've been searching trough the web for a couple of hours. Tried a lot of stuff. Nothing works.
Any ideas on how to do this?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一些问题。
replace
函数允许引用函数作为其第二个参数。您正在调用convert
函数,而不是传递引用。replace
函数不会修改原始字符串。您需要保存其结果。convert
。把它们放在一起:
输出:
There are a few problems.
replace
function allows a reference to a function as its second argument. You're calling theconvert
function, not passing a reference.replace
function does not modify the original string. You need to save its result.convert
before it has been defined.Putting it all together:
Output:
String#replace
不会修改接收者,因为 JavaScript 中的字符串是不可变的。您想要这个:另外,您引用了
Text
而不是我已更正的text
。String#replace
doesn't modify the receiver since strings in JavaScript are immutable. You want this instead:Also, you had a reference to
Text
instead oftext
which I have corrected.