BlogJava 首頁 新隨筆 聯系 聚合 管理
            37 Posts :: 64 Stories :: 21 Comments :: 0 Trackbacks
          Q
          replace() 1
          如何使用 replace() 來替換字符串中的字符。
          replace() 2 - 全局搜索
          如何使用 replace() 進行全局替換。
          replace() 3 - 對大小寫不敏感的搜索
          如何使用 replace() 確保大寫字母的正確性。
          replace() 4
          如何使用 replace() 來轉換姓名的格式。
          replace() 5
          如何使用 replace() 來轉換引號。
          replace() 6
          如何使用 replace() 把單詞的首字母轉換為大寫。

          實例

          例子 1

          在本例中,我們將使用 "W3School" 替換字符串中的 "Microsoft":

          <script type="text/javascript">
          var str="Visit Microsoft!"
          document.write(str.replace(/Microsoft/, "W3School"))
          </script>

          輸出:

          Visit W3School!

          例子 2

          在本例中,我們將執行一次全局替換,每當 "Microsoft" 被找到,它就被替換為 "W3School":

          <script type="text/javascript">
          var str="Welcome to Microsoft! "
          str=str + "We are proud to announce that Microsoft has "
          str=str + "one of the largest Web Developers sites in the world."
          document.write(str.replace(/Microsoft/g, "W3School"))
          </script>

          輸出:

          Welcome to W3School! We are proud to announce that W3School
          has one of the largest Web Developers sites in the world.

          例子 3

          您可以使用本例提供的代碼來確保匹配字符串大寫字符的正確:

          text = "javascript Tutorial";
          text.replace(/javascript/i, "JavaScript");
          

          例子 4

          在本例中,我們將把 "Doe, John" 轉換為 "John Doe" 的形式:

          name = "Doe, John";
          name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");

          例子 5

          在本例中,我們將把所有的花引號替換為直引號:

          name = '"a", "b"';
          name.replace(/"([^"]*)"/g, "'$1'");

          例子 6

          在本例中,我們將把字符串中所有單詞的首字母都轉換為大寫:

          name = 'aaa bbb ccc';
          uw=name.replace(/\b\w+\b/g, function(word){
          return word.substring(0,1).toUpperCase()+word.substring(1);}
          );

          posted on 2009-09-10 10:38 xiachang88 閱讀(265) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 云阳县| 中阳县| 湖州市| 双峰县| 儋州市| 泰顺县| 繁峙县| 郁南县| 哈尔滨市| 雅安市| 花莲县| 德兴市| 甘孜县| 江油市| 凯里市| 双峰县| 永德县| 西昌市| 绥宁县| 新安县| 石渠县| 姜堰市| 静安区| 石阡县| 安吉县| 延安市| 石棉县| 包头市| 昌邑市| 灵武市| 兴业县| 张北县| 华坪县| 淮北市| 大邑县| 贵阳市| 绥阳县| 麟游县| 平陆县| 土默特右旗| 汉沽区|