本文实例讲述了JS基于正则截取替换特定字符之间字符串操作。分享给大家供大家参考,具体如下:
示例1:
<!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=/( @[^ ]* )/g; var reg2=/( #[^#]*# )/g; var reg3=/(#[^#]*#)/g; document.write(html); document.write("<br/>"); html=html.replace(reg1,"<span style='color:red'>$1</span>"); html=html.replace(reg2,"<span style='color:green;'>$1</span>"); document.write(html); document.write("<br/>"); html1 = html1.replace(reg3,"<span style='color:blue;'>$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=/({[^{]*})/g; c = c.replace(reg5,"<span style='color:red'>$1</span>"); document.write(c); document.write("<br/>"); </script> </head> <body > </body> </html>
运行截图如下:
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript正则表达式技巧大全》、《JavaScript替换操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。