例题

1.写出代码,检验一个字符串首尾是否都含有数字?

            var reg = /^\d[\s\S]*\d$/g

            var str ="4fjsdklfjsld6"

  1. 匹配类似于xxyy形式的字符串?

var str = "aabb"

            var reg = /(\w)\1(\w)\2/g  //  (\w)表示子表达式

3.匹配问题

var str = "aa"

                str.replace("a","b")   //结果为ba,只能访问一个,没有访问全局的能力

 

var reg = /[a]/g

                var str = "aa"

                str.replace(reg,”b”)  //结果为bb,用正则表达访问了全局

    给你一个字符串str = “aabb”,将它转换成“bbaa”的形式?

var reg = /(\w)\1(\w)\2/

                var str = "aabb"

                str.replace(reg,"$2$2$1$1")  //$2代表第二个自表达式的引用,$1代表第一个自表达式的引用

var reg = /(\w)\1(\w)\2/g

                var str = "aabb"

               console.log(str.replace(reg,function($,$1,$2){                            return $2+$2+$1+$1

               }))

//形参里第一个$代表接受匹配的全局结果,即aabb,$1代表reg里第一个引用,$2代表第二个引用

4.请把字符串“the_first_name”替换成“theFirstName”

var str = "the-first-name"

                var reg = /-(\w)/g

                str.replace(reg,function($,$1){

                     return $1.toUpperCase()

               })

 

  1. var str = "abaaaaaaa"

                 var reg = /a(?=b)/g

正向预查,正向断言。找到后面有ba字符

  1. 请把字符串aaaaaaabbbbbbbcccccc替换成abc

                 var str = "aaaaaaaabbbbbbbcccccc"

                 var reg = /(\w)\1*/g

  1. 请将10000000000”转换成“100.000.000”形式

var str = "10000000000"

                var reg = /(?=(\B)(\d{3})+$)/g

                console.log(str.replace(reg,"."))

  1. 写一个deepClone函数

var obj = {

name : "abc",

age : 123,

card : ['visa','unionpay'],

wife : {

name : "bcd",

son : {

name : "aaa"

}

}

}

 

var obj1 = {

 

}

 

function deepClone(origin,target) {

var target = target || {},

    toStr = Object.prototype.toString,

    arrStr = "[object Array]"

for(var prop in origin){

if(origin.hasOwnProperty(prop)){

if(origin[prop] !== "null" && typeof(origin[prop]) == 'object'){

if(toStr.call(origin[prop]) == arrStr){

target[prop] = []

}else{

target[prop] = {}

}

deepClone(origin[prop],target[prop])

}else{

target[prop] = origin[prop]

}

}

}

return target

}

 

posted @ 2017-12-17 06:37  追丨追  阅读(193)  评论(0编辑  收藏  举报