现在的位置: 首页 > 综合 > 正文

javascript的正则匹配

2013年10月15日 ⁄ 综合 ⁄ 共 1884字 ⁄ 字号 评论关闭

<script language="javascript">
function RegexText()
{
   var r, re,keywords,description;                     // 声明变量。
   keywords=document.Frm.keywords.value;
   description=document.Frm.description.value;
   var s = document.Frm.Txt.value;   
   re = new RegExp("<META.*?name=keywords>","i");  // 创建正则表达式对象。
   r = s.match(re);               // 在字符串 s 中查找匹配。
   //有结果替换,无结果插入
   
   if(r!=null)
   {
      s=s.replace(r,"<META content="+keywords+" name=keywords>")
   }
   else
   {
     s=s.replace("</title>","</title><META content="+keywords+" name=keywords>/r/n")
   }
  
   //<META content=财政,h name=description>
   re=new RegExp("<META.*?name=description>","i");
   r=s.match(re);
   if(r!=null)
   {
      s=s.replace(r,"<META content="+description+" name=description>")
   }
   else
   {
     s=s.replace("</title>","</title><META content="+description+" name=description>/r/n")
   }
   document.Frm.Txt.value=s
}

function GetTextFromFile()
{
   var r, re,keywords,description;     
   var s = document.Frm.Txt.value; 
   re = new RegExp("<META content=(.*?)name=keywords>","i");  // 创建正则表达式对象。
   r = s.match(re);   
   if(r!=null && r.length>1)
   {
      document.Frm.keywords.value=r[1];
   }
   else
   {
     document.Frm.keywords.value="";
   }
   
   re=new RegExp("<META content=(.*?)name=description>","i");
   r=s.match(re);
   if(r!=null && r.length>1)
   {
      document.Frm.description.value=r[1];
   }
   else
   {
     document.Frm.description.value="";
   }
}
</script>
<form action="" method="post" id="Frm" name="Frm">
  <label>
  <textarea name="Txt" cols="60" rows="5" id="Txt"></title><META content=中国,银行,政府 name=description>
  <META content=中国,银行 name=keywords></textarea>
  </label>
<br />
  关键字:
  <input name="keywords" type="text" id="keywords" value="中国,银行" />
  描述:
    <input name="description" type="text" id="description" value="中国,银行,政府" />
  </label>
  <br />
    <input name="Input" type="button" onclick="RegexText()" value="设置" />
    <input name="Output" type="button" onclick="GetTextFromFile()" value="提取" />    
</form>

 

【上篇】
【下篇】

抱歉!评论已关闭.