JS interception string method and object null

The js object judges whether it is empty:

Object.keys(obj) can be used in 1.es6

var data = {};
var arr = Object.keys(data);
alert(arr.length == 0); //true 为空, false 不为空

2. Convert the json object into a json string, and then judge whether the string is "{}"

var data = {};
var b = (JSON.stringify(data) == "{}");
alert(b);   //true 为空, false 不为空

 

JS provides three methods for intercepting strings, namely: slice(), substring() and substr(), all of which can accept one or two parameters:

var stmp = "rcinn.cn";

  • Use a parameter

alert(stmp.slice(3));//From the 4th character, intercept to the last character; return "nn.cn"

alert(stmp.substring(3));//From the 4th character, intercept to the last character; return "nn.cn"

  • Use two parameters

alert(stmp.slice(1,5))//From the 2nd character to the 5th character; return "cinn"

alert(stmp.substring(1,5));//From the 2nd character to the 5th character; return "cinn"

  • If only one parameter is used and it is 0, then the entire parameter is returned

alert(stmp.slice(0));//return the entire string

alert(stmp.substring(0));//return the entire string

  • Return the first character

// 1. Bit-bit interception

alert(stmp.slice(0,1));//return "r"

alert(stmp.substring(0,1));//return "r"

//In the above example, we can see that the usage of slice() and substring() is the same, and the returned value is also the same.

//But when the parameters are negative, their return values ​​are different, see the following example

alert(stmp.slice(2,-5));//returns "i"; actually slice(2,3), negative number plus string length is converted to positive 3, (if the first digit >= the second digit , It returns an empty string);

alert(stmp.substring(2,-5));//returns "rc"; actually it is substring(2,0), negative numbers are converted to 0, and substring always takes the smaller number as the starting position.

 

// 2. Bit-bit interception and bit-bit interception

alert(stmp.substring(1,5))//Start from the first position, intercept to the fifth position; return "cinn"

alert(stmp.substr(1,5)); //From the first position, intercept 5 characters; return "cinn."

var phone = 15989012100;

phone.slice(-6) Take the last 6 digits (the second parameter does not need to write 0), return '012100';

phone.slice(-6, -4) Take the last 4 digits to the last 6 digits, (-6+11, -4+11)=(5,7);

// 日期比较大小 当日期每个月都小1时
var nowdate = new Date();
item = 2016-7-16;
temp = item.split('-');
if (temp[0] != curYear || temp[1] != curMonth) {
    return;
}
temp[1] = parseInt(temp[1]) + 1;
date = new Date(temp.join('-'));
if(date>=nowdate){
执行A;
}else{
执行B;
}

Replace the letters after the specified string

var abc = 'adadada=ss';
var j = abc.substring(abc.indexOf('=')+1,abc.length);
var dsd =abc.replace(j,'haha');  -->   dsd = 'adadada=haha'

 

Guess you like

Origin blog.csdn.net/AN0692/article/details/108823055