zoukankan      html  css  js  c++  java
  • 代码-JS之正则replace函数

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    
    <script>
        /*************** 加入全局的g表示替换所有符合条件的 ***************/
            var str1 = 'php php';
            var r1 = /h/g;
            var result1 = str1.replace(r1, 'H');
            console.log(result1);   //结果:pHp pHp
    
        /*************** 带有子表达式的例子 ***************/
            var str2 = 'php7 and ES5';
            var r2 = /(d)/g;
            var result2 = str2.replace(r2, '$1$1');
            console.log(result2);   //结果:php77 and ES55
    
        /*************** $` 表示捕获的左侧的内容,$' 表示捕获的右侧的内容 ***************/
        //替换abc为a[a-b-c]c
            var str3 = 'nba';
            var result3 = str3.replace(/(b)/g, "[$`-$1-$']");
            console.log(result3);   //结果:n[n-b-a]a
    
        /*************** 复杂的替换,可以使用函数 ***************/
        //替换aaa bbb ccc为Aaa Bbb Ccc
        var str = 'aaa bbb ccc';
        //console.log(str.match(/[a-z]+/g));  // [ "aaa", "bbb", "ccc" ]
        //形参x表示每次匹配的结果
        var result = str.replace(/[a-z]+/g, function(x){
            //使用substr()函数从零截取到一,从一截取到最后
            return x.substr(0,1).toUpperCase() + x.substr(1);
        });
        console.log(result);    //结果:Aaa Bbb Ccc
        
    </script>
    
    </body>
    </html>
    
    Copyright [2018] by [羊驼可以吃吗] form [https://www.cnblogs.com/phpisfirst/]
  • 相关阅读:
    hdu 1028 Ignatius and the Princess III (n的划分)
    CodeForces
    poj 3254 Corn Fields (状压DP入门)
    HYSBZ 1040 骑士 (基环外向树DP)
    PAT 1071 Speech Patterns (25)
    PAT 1077 Kuchiguse (20)
    PAT 1043 Is It a Binary Search Tree (25)
    PAT 1053 Path of Equal Weight (30)
    c++ 常用标准库
    常见数学问题
  • 原文地址:https://www.cnblogs.com/phpisfirst/p/9819128.html
Copyright © 2011-2022 走看看