zoukankan      html  css  js  c++  java
  • JS字符串常用方法(自)---7、字符串替换

    JS字符串常用方法(自)---7、字符串替换

    一、总结

    一句话总结:

    字符串替换方法有replace(regexp,newSubStr),作用是用新的字符串替换原字符串中的内容,参数是regexp(正则表达式)和newSubStr(新的字符串)
    replace(regexp,newSubStr)
    作用:用新的字符串替换原字符串中的内容
    参数:regexp(正则表达式),newSubStr(新的字符串)
    返回值:替换好之后的字符串
    
    //在 replace() 中使用正则表达式
    var str = 'Twas the night before Xmas...';
    var newstr = str.replace(/xmas/i, 'Christmas');
    console.log(newstr);  // Twas the night before Christmas...

    1、replace(regexp,newSubStr)方法交互字符串中的两个单词 实例?

    可以在替换字符串中插入特殊变量名:比如$2,$1:var newstr = str.replace(re, "$2, $1");
    //交换字符串中的两个单词
    var re = /(w+)s(w+)/;
    var str = "John Smith";
    var newstr = str.replace(re, "$2, $1");
    console.log(newstr);// Smith, John

    二、字符串替换

    博客对应课程的视频位置:

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>replace()</title>
     6 </head>
     7 <body>
     8 <!--
     9 
    10 replace(regexp,newSubStr)
    11 作用:用新的字符串替换原字符串中的内容
    12 参数:regexp(正则表达式),newSubStr(新的字符串)
    13 返回值:替换好之后的字符串
    14 
    15 -->
    16 <script>
    17     //在 replace() 中使用正则表达式
    18     // var str = 'Twas the night before Xmas...';
    19     // var newstr = str.replace(/xmas/i, 'Christmas');
    20     // console.log(newstr);  // Twas the night before Christmas...
    21 
    22     //交换字符串中的两个单词
    23     var re = /(w+)s(w+)/;
    24     var str = "John Smith";
    25     var newstr = str.replace(re, "$2, $1");
    26     console.log(newstr);// Smith, John
    27 
    28 </script>
    29 </body>
    30 </html>
     
  • 相关阅读:
    wpf中DataGrid自定义验证(包含BindingGroup)
    WPF博客地址分享
    ComboBox在WPF中的绑定示例:绑定项、集合、转换,及其源代码
    【windows phone】CollectionViewSource的妙用
    WPF之Binding深入探讨
    正确理解WPF中的TemplatedParent
    继续聊WPF——获取ComboBox中绑定的值
    WPF触发器(Trigger、DataTrigger、EventTrigger)
    jQuery和javaScript页面加载完成时触发的事件
    jQuery对象和dom对象的转换
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12691244.html
Copyright © 2011-2022 走看看