2015-08-22 96 views
0

我有这个代码获取查询字符串值并将其显示在h3中。我试图将URL中的任何%20更改为空格。我试过使用.replace,但它不起作用。用html替换文本?

<h3 style="text-decoration: underline;margin-left:10px;color:white;position: absolute; 
     z-index: 999;"> 
     <script> 
      function frtitlen(frtitle) { 
       frtitle = frtitle.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); 
       var regexS = "[\\?&]" + frtitle + "=([^&#]*)"; 
       var regex = new RegExp(regexS); 
       var results = regex.exec(window.location.href); 

       if (results == null) return "Untitled"; 
       else { 

        return results[1]; 
       } 
      } 
     </script> 
     <script> 
      document.write(frtitlen('frtitle')); 
     </script> 
    </h3> 
+1

使用decodeURIComponent来解码转义字符,比试图使用regexp更容易 –

回答

0

在JavaScript中反复更换的最佳选择是使用分割和结合​​功能结合在一起,分割()函数的分隔符打破串入一个数组和join()函数加入数组的分隔符, replace()函数只在整个字符串中替换文本一次。

<script> 
    //This is the best substitute for the replace repeatedly. 
    str.split(delimiter).join(your_own_delimiter); 
    </script> 

说例如你有一个字符串,你想用连字符替换空格,那么你可以替换它中的所有空格,如下所示。

<script> 
    var your_string="This is my demo string."; 
    output_string=your_string.split(' ').join('-'); 
    console.log(output_string); //Final Output: This-is-my-demo-string. 
    </script>