Javascript 将()替换为数组元素上的RegExp
我想编写一个JavaScript函数,将一些简单的BBcode标记(如[red][/red])转换为Html标记。我认为replace()函数是最好的方法。我编写了一个简单的testfunction来尝试它,但它似乎不起作用Javascript 将()替换为数组元素上的RegExp,javascript,regex,replace,Javascript,Regex,Replace,我想编写一个JavaScript函数,将一些简单的BBcode标记(如[red][/red])转换为Html标记。我认为replace()函数是最好的方法。我编写了一个简单的testfunction来尝试它,但它似乎不起作用 /** * @function * @description Replaces the bb-tags with html-tags */ function bbToHtml(form) { debugger var text = form.text.va
/**
* @function
* @description Replaces the bb-tags with html-tags
*/
function bbToHtml(form) {
debugger
var text = form.text.value;
bbTags = new Array("[red]", "[yellow]", "[green]", "[/red]", "[/yellow]", "[/green]");
htmlTags = new Array("<font color='red'>", "<font color='yellow'>", "<font color='green'>", "</font>", "<font>", "</font>");
for (var i = 0; i < bbTags.length; i++) {
var re = new RegExp(bbTags[i], "g");
text = text.replace(re, htmlTags[i]);
}
alert(text);
}
/**
*@函数
*@description将bb标记替换为html标记
*/
函数bbToHtml(表单){
调试器
var text=form.text.value;
bbTags=新数组(“[red]”、“[yellow]”、“[green]”、“[/red]”、“[/yellow]”、“[/green]”);
htmlTags=新数组(“,”,“,”,“,”,“,”);
对于(var i=0;i
它应该将“[red]hello[/red]”
转换为“hello”
,但它只是给了我一个奇怪的字符串
怎么了?我认为这与我的正则表达式有关。
[
和]
在正则表达式中有特殊意义,需要转义,而且您不需要像编写代码那样使用正则表达式,只需执行以下操作:
function bbToHtml(form) {
debugger
var text = form.text.value;
bbTags = new Array("[red]", "[yellow]", "[green]", "[/red]", "[/yellow]", "[/green]");
htmlTags = new Array("<font color='red'>", "<font color='yellow'>", "<font color='green'>", "</font>", "<font>", "</font>");
for (var i = 0; i < bbTags.length; i++) {
while(text.indexOf(bbTags[i])!==-1){
text = text.replace(bbTags[i], htmlTags[i]);
}
}
alert(text);
}
并反复进行
如果您希望也可以转义正则表达式,请参阅,以获取一个实现此功能的函数
您也可以手动执行此操作<代码>“[red]”变为“\[red\]”
(括号转义) 只要换一行就行了
text = text.replace(re, htmlTags[i]);
进入
删除无用的代码
replace
也可以将“normal”(不是regex)值用作参数。如果您想使用regex,可以简化很多。无阵列或循环:
var str = '[red]foo[/red] hello world [blue]hey[/blue]',
re = /\[(\w+)\](.*)\[\/\1\]/g;
str = str.replace(re, '<font color="$1">$2</font>');
console.log(str);
//^ <font color="red">foo</font> hello world <font color="blue">hey</font>
var str='[red]foo[/red]hello world[blue]hey[/blue],
re=/\[(\w+)\](.*)\[\/\1\]/g;
str=str.replace(关于“$2”);
console.log(str);
//^福你好,世界嘿
另外,作为旁注,
font
已经很少使用了,我建议你在类中使用span
。你能把你的“It should convert”。。。在代码块中-我认为有一些html结构没有出现在问题中。另外,你能告诉我“奇怪的字符串”是什么吗?是的,奇怪的字符串是什么?它是这样的,但是更长:第二个“
不应该是”
?如果你不使用regexp,它只会替换第一个匹配项,而不是所有匹配项。但它只替换第一个匹配项,而不是所有匹配项。
text = text.replace(bbTags[i], htmlTags[i]);
var str = '[red]foo[/red] hello world [blue]hey[/blue]',
re = /\[(\w+)\](.*)\[\/\1\]/g;
str = str.replace(re, '<font color="$1">$2</font>');
console.log(str);
//^ <font color="red">foo</font> hello world <font color="blue">hey</font>