<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Test</title> <script type="text/javascript" language="javascript" > var html="ssssss @用户名 和话题 #话题标题# 用不同颜色高@假的亮 @用户名2 和sss#此话题不对呀#ss"; var html1="ssssss @用户名 和话题 #话题标题# 用不同颜色高@假的亮 @用户名2 和sss#此话题不对呀#ss"; var reg1=https://www.jb51.net/( @[^ ]* )/g; var reg2=https://www.jb51.net/( #[^#]*# )/g; var reg3=https://www.jb51.net/(#[^#]*#)/g; document.write(html); document.write("<br/>"); html=html.replace(reg1,"<span>$1</span>"); html=html.replace(reg2,"<span>$1</span>"); document.write(html); document.write("<br/>"); html1 = html1.replace(reg3,"<span>$1</span>"); document.write(html1); document.write("<br/>"); </script> </head> <body > </body> </html>
运行截图如下:
示例2:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Test</title> <script type="text/javascript" language="javascript" > var a = "20141021123212"; var reg4 = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/; a = a.replace(reg4,"$1-$2-$3 $4:$5:$6"); document.write(a); document.write("<br/>"); </script> </head> <body > </body> </html>
运行截图如下:
示例3:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Test</title> <script type="text/javascript" language="javascript" > var c ="好啊 {话题标题} 用不同颜色sss{此话题好}ss"; var reg5=https://www.jb51.net/({[^{]*})/g; c = c.replace(reg5,"<span>$1</span>"); document.write(c); document.write("<br/>"); </script> </head> <body > </body> </html>
运行截图如下:
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript正则表达式技巧大全》、《JavaScript替换操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》