JS基于正则截取替换特定字符之间字符串操作示例

2017-02-10 15:53:19 JavaScript
本文实例讲述了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>

运行截图如下:



希望本文所述对大家Javascript程序设计有所帮助。