将[url]标记替换为< a href> Javascript/JQuery中的标签 [英] Replace [url] tags with <a href> tags in Javascript/JQuery
本文介绍了将[url]标记替换为< a href> Javascript/JQuery中的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用JQuery来实现以下逻辑:
I'm trying to use JQuery to achieve the following logic:
- 将
[url="http://www.google.com"]Google[/url]
的字符串值替换为<a href="http://www.google.com">Google</a>
- Replace the string value of
[url="http://www.google.com"]Google[/url]
with<a href="http://www.google.com">Google</a>
请在下面查看我的HTML页面.问题在于,按下按钮时,仅粘贴原始文本,而没有进行RegEx替换.
Please see my HTML page below. The problem is that on pressing the button, the orignal text is just pasted and no RegEx replacements are made.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
//<![CDATA[
function processJs() {
var oldtext = $("#oldtext").html();
var newtext = oldtext.replace('\[url\s?=\s?"?(.*?)"?\](.*?)\[\/url\]', '<a href="$1">$2</a>');
$('#mydiv').html(newtext);
}
//]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="oldtext">
Try this funky new search engine:
[url="http://www.google.com"]Google[/url]
Or this older one from back in the day:
[url="http://uk.altavista.com"]AltaVista[/url]
</div>
<div>
<input type="button" id="btn" value="Replace" onclick="processJs(); return false;" />
</div>
<div id="mydiv" style="background-color: #eeeeee; border: 2px inset #aaaaaa">
Replaced text will go here.
</div>
</form>
</body>
</html>
我已经使用ASP.NET来运行RegEx模式,所以我不确定移植到JavaScript时问题出在哪里...
I've had this RegEx pattern work using ASP.NET, so I'm not sure where the problem lies when ported to JavaScript...
推荐答案
那不是有效的正则表达式.使用/
作为修饰符:
That is not a valid regex. Use /
as modifiers:
/\[url\s?=\s?"?(.*?)"?\](.*?)\[\/url\]/
创建功能:
function processJs() {
var oldtext = $("#oldtext").html();
var newtext = oldtext.replace(/\[url\s?=\s?"?(.*?)"?\](.*?)\[\/url\]/g, '<a href="$1">$2</a>');
$('#mydiv').html(newtext);
}
最后的
g
将在文本上重复它.这是一个小提琴: http://jsfiddle.net/xe2F9/
g
at the end will repeat it over the text. Here is a fiddle: http://jsfiddle.net/xe2F9/
这篇关于将[url]标记替换为< a href> Javascript/JQuery中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文