ES6 string extension + regular extension + numerical extension

Template string

``Back quote

    var cyy={
        name:"cyy",
        age:18,
        say:function(){
            console.log('My name is'+this.name+',I am this year'+this.age+'year');
        },
        say2:function(){
            console.log(`My name is`+this.name+`,I am this year`+this.age+`year`);//Template strings can replace single or double quotes
        },
        say3:function(){
            console.log(`My name is ${ this.name },I am this year ${ this.age }year`);//Can use ${}Alternative string splicing
        },
        say4:function(){
            console.log(`My name is ${ `Miss ${this.name}` },I am this year ${ this.age }year`);//${}Nested
        },
        say5:function(){
            console.log(`My name is ${ `Miss ${this.name.toUpperCase()}` },I am this year ${ this.age }year`);//${}You can use the string method
        }
    }
    cyy.say();
    cyy.say2();
    cyy.say3();
    cyy.say4();
    cyy.say5();

 

 

Render data in normal mode

//simulation ajax Get data
function getList(){
    //ajax
    
    return {
        status:true,
        msg:"Get success",
        data:[{
            id:1,
            title:"title1",
            date:"date1"
        },{
            id:2,
            title:"title2",
            date:"date2"
        },{
            id:3,
            title:"title3",
            date:"date3"
        }]
    };
}

//Structure assignment gets data (to data Alias listData)
const {data:listData,msg,status}=getList();

if(status){
    let arr=[];

    //Cycle to get data
    listData.forEach(function({title,date}){
        //Render data in normal mode
        arr.push('<li>\
                    <span>'+title+'</span>\
                    <span>'+date+'</span>\
                </li>');
    })

    let ul=document.createElement("ul");
    //join Array to string
    //arr.join('') String splicing
    //arr.join() Strings are separated by commas 
    ul.innerHTML=arr.join('');
    document.body.appendChild(ul);

}else{
    alert(msg);
}

 

Render data using template strings (line wrapping is possible without escaping)

//simulation ajax Get data
function getList(){
    //ajax
    
    return {
        status:true,
        msg:"Get success",
        data:[{
            id:1,
            title:"title1",
            date:"date1"
        },{
            id:2,
            title:"title2",
            date:"date2"
        },{
            id:3,
            title:"title3",
            date:"date3"
        }]
    };
}

//Structure assignment gets data (to data Alias listData)
const {data:listData,msg,status}=getList();

if(status){
    let arr=[];

    //Cycle to get data
    listData.forEach(function({title,date}){
        //Template string rendering data
        arr.push(`<li>
                    <span>${ title }</span>
                    <span>${ date }</span>
                </li>`);
    })

    let ul=document.createElement("ul");
    //join Array to string
    //arr.join('') String splicing
    //arr.join() Strings are separated by commas 
    ul.innerHTML=arr.join('');
    document.body.appendChild(ul);

}else{
    alert(msg);
}

 

 

You can also further process the template string

//simulation ajax Get data
function getList(){
    //ajax
    
    return {
        status:true,
        msg:"Get success",
        data:[{
            id:1,
            title:"title1",
            date:"date1"
        },{
            id:2,
            title:"title2",
            date:"date2"
        },{
            id:3,
            title:"title3",
            date:"date3"
        }]
    };
}

//Structure assignment gets data (to data Alias listData)
const {data:listData,msg,status}=getList();

function foo(str){
    return str.replace("date","mydate");
}

if(status){
    let arr=[];

    //Cycle to get data
    listData.forEach(function({title,date}){
        //Template string rendering data
        arr.push(`<li>
                    <span>${ `Course name ${ title }` }</span>
                    <span>${ foo(date) }</span>
                </li>`);
    })

    let ul=document.createElement("ul");
    //join Array to string
    //arr.join('') String splicing
    //arr.join() Strings are separated by commas 
    ul.innerHTML=arr.join('');
    document.body.appendChild(ul);

}else{
    alert(msg);
}

 

 

New method of string part

padStart padEnd completion string length

//padStart Complete from the front
//The first parameter is the total length after completion, and the second parameter is the string used for completion
let str="cyy";
let str2=str.padStart(8,"nice ");
let str3=str.padStart(13,"nice ");

 

 

//padEnd Complete from the back
//The first parameter is the total length after completion, and the second parameter is the string used for completion
let str="cyy";
let str2=str.padEnd(8," nice");
let str3=str.padEnd(13," nice");

 

 

repeat string repetition

{
    let str="c";
    console.log(str.repeat(10));//Repeat 10 times.

    let str2="cyy ";
    console.log(str2.repeat(4));//Repeat 4 times.
}

 

Note that repeat will report an error if a negative number less than - 1 is passed in, such as - 3

If a negative number greater than - 1 is passed in, such as - 0.33, it will turn to 0

If a decimal is passed in, such as 2.55, it will be rounded (round down, turn to 2)

 

Encapsulate functions to implement repeat like functions

{

    console.log(myRepeat("s",10));//Repeat 10 times.

    function myRepeat(str,num){
        // Define an array, the number of elements is num+1
        // Then the array is converted to a string, and the str As separator
        return new Array(num+1).join(str);
    }
}

 

 

startsWith endsWidth determines whether the string starts with and ends with

{
    let str="i am cyy";
    console.log(str.startsWith("i"));
    console.log(str.endsWith("yy"));
}

 

 

Include judgment exists

indexOf can also achieve similar functions

{
    let str="i am cyy";
    if(str.indexOf("cyy") !== -1){
        console.log(`existence cyy`);
    }

    //~x=!(x+1)  -1 It will turn to 0.
    if(~str.indexOf("cyy")){
        console.log(`existence cyy`);
    }

    if(str.includes("cyy")){
        console.log(`existence cyy`);
    }
}

 

Traversal string before ES6

{
    let str="i am cyy";
    //Traversal in the original way
    for(var i=0,len=str.length;i<len;i++){
        console.log(str[i]);
        //charAt Characters can also be returned by Subscripts
        console.log(str.charAt(i));
    }
    
}

 

 

String to array, using slice of array prototype

{
    let str="i am cyy";
    //String to array
    let str2=Array.prototype.slice.call(str);
    console.log(str2);

    let str3=str.split("");
    console.log(str3);

    //Extended operator
    let str4=[...str];
    console.log(str4);

    //Extension operator 2
    let [...str5]=str;
    console.log(str5);

    //Traversing array
    str5.forEach(function(w){
        console.log(w);
    })
    
}

 

 

for in traverses the properties of an object or array

New for of ES6, only arrays can be traversed, not objects

forEach only traverses arrays, not objects

for traversal array common

 

Traversal operation string (using array mode)

Encrypt uppercase letters in strings

{
    //Method 1
    const map={
        A:"100",
        B:"99",
        C:"98",
        D:"97",
        E:"96",
        F:"95",
        G:"94"
    };
    const words="ABCDEFG";
    
    let str="I AM CYY";
    let ostr=[...str];//String to array

    ostr.forEach(function(word,index){
        if(words.includes(word)){
            ostr[index]=map[word];
        }
    })
    console.log(ostr);
    console.log(ostr.join(""));//Concatenate back string
}

 

 

Traversing strings with for of

    //for of Traversal string
    let str="I AM CYY";
    for(let s of str){
        console.log(s);
    }

 

 

Using for of to realize data encryption

{

    //for of Implement character encryption
    const map={
        A:"100",
        B:"99",
        C:"98",
        D:"97",
        E:"96",
        F:"95",
        G:"94"
    };
    const words="ABCDEFG";
    
    let str="I AM CYY";
    let nstr="";

    for(let s of str){
        if(words.includes(s)){
            nstr+=map[s];
        }else{
            nstr+=s;
        }
    }

    console.log(nstr);
}

 

 

 

unicode notation

{

    //unicode Code point  \u
    //Generally only recognize 0000-ffff
    //Because it can recognize four bits,\u1f43 yesὃ,Follow 6
    let str="\u1f436";
    console.log(str);

    //ES6 It is allowed to put curly brackets on code points, so that all code points will be identified and will not be truncated in four digits
    let str2="\u{1f436}";
    console.log(str2);
}

 

 

Remember to put quotation marks on the console input test

 

 

codePointAt gets the code point corresponding to a character in the string

{

    //unicode Code point  \u
    //Generally only recognize 0000-ffff
    //Because it can recognize four bits,\u1f43 yesὃ,Follow 6
    let str="\u1f436";
    console.log(str);

    //ES6 It is allowed to put curly brackets on code points, so that all code points will be identified and will not be truncated in four digits
    let str2="\u{1f436}";
    console.log(str2);

    console.log("🐶".codePointAt(0));//128054
    console.log("🐶".codePointAt(0).toString(16));//1f436  Get the code point, then convert to hexadecimal
}

 

 

at takes characters based on Subscripts

{
    console.log("🐶123".at(0));
}

 

This chrome browser does not support it. It needs to be compiled into ES5 code

 

Regular extension (u, y modifier)

There are three ways to create a regular:

{
    const pattern1=/^c/g;
    const pattern2=new RegExp("^c","g");
    const pattern3=new RegExp(/^c/g);
}

 

{
    const pattern1=/^c/g;
    const pattern2=new RegExp("^c","g");
    const pattern3=new RegExp(/^c/g);

    console.log("cyy".match(pattern1));
    console.log("vyy".match(pattern1));
}

 

 

Modifier u unicode

If you do not use the u modifier, if two characters are different when matching, but there is an inclusion condition in unicode, an error will occur

{

    console.log(/^\ud83d/.test("\ud83d\udc36"));//true
    
}

 

 

{

    console.log(/^\ud83d/.test("\ud83d\udc36"));//true

    //Use u Modifier, correct judgment unicode
    console.log(/^\ud83d/u.test("\ud83d\udc36"));//false
}

 

 

y glue modifier (must match continuously after one match, next to the end of the last match)

{

    const r1=/cyy/g;
    const r2=/cyy/y;
    const str="cyycyy-cyy";

    console.log(r1.exec(str));
    console.log(r1.exec(str));
    console.log(r1.exec(str));
    console.log(r1.exec(str));

    console.log("----------------------");

    console.log(r2.exec(str));
    console.log(r2.exec(str));
    console.log(r2.exec(str));
}

 

 

{

    let text="\ud83d\udc36";

    //.It means to match any character. After adding the first and last restrictions, the string to be matched can only be one character
    // however'\ud83d\udc36'Is two characters, so cannot match to, return false
    console.log(/^.$/.test(text));//false

    //Add to u After that, it will identify text Of unicode Is a character, so it can be matched to
    console.log(/^.$/u.test(text));//true
}

 

 

Numerical expansion

New base representation:

{

    //0o 0O octonary Octal number system
    //0b 0B binary Binary system
    
    // Previously, 016 was 14
    // In order to avoid misunderstanding, the octal is specified as 0 o Start, binary 0 b start
    
    console.log(016);//Report errors
    console.log(0o16);//14
    console.log(0b1111);//15
}

 

New methods and security numbers:

Put parseInt and parseFloat on the Number from the window

{

    //Originally hung on window upper
    console.log(window.parseInt(1.22));
    console.log(window.parseFloat(1.22));

    //window It can be omitted.
    console.log(parseInt(1.22));
    console.log(parseFloat(1.22));

    //ES6 Here we are. Number upper
    console.log(Number.parseInt(1.22));
    console.log(Number.parseFloat(1.22));
}

 

 

Is isNaN non numeric

{

    
    console.log(Number.isNaN(NaN));
    console.log(Number.isNaN(-NaN));
    console.log(Number.isNaN("1"));
    console.log(Number.isNaN(1));
    console.log(Number.isNaN(null));
    console.log(Number.isNaN(false));
}

 

 

Implement isNaN in its own way

{

    
    console.log(myNaN(NaN));
    console.log(myNaN(-NaN));
    console.log(myNaN("1"));
    console.log(myNaN(1));
    console.log(myNaN(null));
    console.log(myNaN(false));

    function myNaN(value){
        //NaN Is not equal to itself
        return value !== value;
    }
}

 

 

Is isfinish Limited

Max safe integer

Min safe inter

Is isSafeInteger a safe number

{

    //Is it limited
    console.log(Number.isFinite(NaN));
    console.log(Number.isFinite(Infinity));
    console.log(Number.isFinite(2/0));
    console.log(Number.isFinite(1));
    console.log(Number.isFinite("123"));
    console.log(Number.isFinite(true));

    console.log(Number.MAX_SAFE_INTEGER);//Maximum safety number
    console.log(Number.MIN_SAFE_INTEGER);//Minimum safety number
    console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER-1));//Is it a safe number
    console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER+1));


}

 

 

Power operation * *

{

    let a=2**10;//2 The 10 time
    console.log(a);//1024

    //Right combination is the default, and 0 times of 10 are calculated first
    let b=2**10**0;
    console.log(b);//2

    //Change the order of operations with parentheses
    let c=(2**10)**0;
    console.log(c);//1
}

Keywords: Javascript less

Added by inrealtime on Wed, 25 Mar 2020 11:16:24 +0200