es6--extension of string, regular, numeric, array

Source: Internet
Author: User
Tags instance method

Third, extended character encoding of strings

Inside JavaScript, characters are stored in UTF-16 format, with each character fixed at 2 bytes. For characters that require 4 bytes of storage (Unicode code points greater than 0xFFFF characters), JavaScript considers them to be two characters. However, Chinese characters tend to be 4 bytes of storage, which is a bit cumbersome to ES6 before processing.

Example: Character encoding

var"李刚";var"ligang";ChineseName.codePointAt(1);     // 0x26446 0x21018String.fromCodePoint(26446);    // 李

* * Note: The **fromcodepoint method is defined on a string object, while the Codepointat method is defined on the instance object of the string.

/* 返回字符串给定位置的字符 */ChineseName.at(0);// 李EnglishName.at(0);// l

See:"garbled, garbled"

Find function
    • Includes (): Returns a Boolean value that indicates whether the parameter string was found.
    • StartsWith (): Returns a Boolean value that indicates whether the parameter string is in the header of the source string.
    • EndsWith (): Returns a Boolean value that indicates whether the parameter string is at the end of the source string.

Example:

var"my name is ligang";str.indexOf("ligang");  // 11str.includes("ligang"// truestr.startsWith("my");   // truestr.endsWith("ligang"// true
Repeat ()

The Repeat method returns a new string indicating that the original string is repeated n times.

"x".repeat(3);  // xxx

"JavaScript up to a specified number of bits" for an extensible solution that can be made more concise

Example: Extensible solution-repeat Implementation

/*** 可扩充的解决方案* @param bits 格式化位数* @param identifier 补全字符* @param value 值*/function dataLeftCompleting(bits, identifier, value){   value = identifier.repeat(bits) + value;   return value.slice(-bits);}
Padstart (), Padend ()

The function of the full length of the string complement. If a string does not have a specified length, it is complete at the head or tail. The Padstart is used for head completion and padend for tail completion.

"1".padStart(3"0");   // 001"123".padStart(3"0"// 001

The above to the specified number of digits problem does not exist!!!

Template string

The template string, which is an enhanced version of the string, is identified with an inverse quotation mark ('). It can be used as a normal string, or it can be used to define a multiline string, or to embed a variable in a string.

let p = {    ‘ligang‘,    25};// 常规方法:字符串与变量拼接使用“+”console.log(‘my name is ‘‘, my age is ‘ + p.age);// 模板字符串:直接使用“`”console.log(my name is ${p.name}, my age is ${p.age});

Example: Support for line wrapping

var sql =   "slect * from Users " +  "where name = ‘ligang‘";const sql =   `slect * from Users   ‘ligang‘;`
Iv. expansion of the regular

There are 4 methods for string objects in JavaScript, and you can use regular expressions: match (), replace (), search (), and split (). ES6 These 4 methods, all within the language to call the RegExp instance method, so that all the regular-related methods, all defined on the RegExp object.

    • String.prototype.match Call Regexp.prototype[symbol.match]
    • String.prototype.replace Call Regexp.prototype[symbol.replace]
    • String.prototype.search Call Regexp.prototype[symbol.search]
    • String.prototype.split Call Regexp.prototype[symbol.split]

There are 3 modifiers in the Regular: G Global match, I ignore case, M multi-line match; new u in ES6 to correctly handle Unicode characters greater than \uffff, y "adhesion" modifier, and the last match starts at the next position where the last match succeeded.

RegExp constructor function
// 在ES5中RegExp构造函数只能接受字符串作为参数varnewRegExp("xyz""i"// ES6允许RegExp构造函数接受正则表达式作为参数,这时会返回一个原有正则表达式的拷贝varnewRegExp(/xyz/i
u modifier
/\u{61}/.test(‘a‘// false/\u{61}/u.test(‘a‘// true
Y modifier

The Y modifier acts like the G modifier and is a global match, and the last match starts at the next position where the last match was successful. The difference is that the G modifier is available only if there is a match in the remaining position, and the Y modifier ensures that the match must start at the remaining first position, which is the meaning of "adhesion".

var"aa_a";var/a+/g;var/a+/y;// 全局匹配// ["aa"]// ["a"]// 粘连匹配// ["aa"]// null
Flags Property

You can get the body of the expression through source, flags gets the modifier for the expression.

/xyz/ig.source;// ‘xyz‘/xyz/ig.flags;// ‘gi‘
String escape
// 原始方法function escapeRegExp(str) {return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g"\\$&");}escapeRegExp(‘http://blog.csdn.net/ligang2585116‘);//‘http:\\/\\/blog\\.csdn\\.net\\/ligang2585116‘// 存在风险,没有被纳入ES7RegExp.escape(‘http://blog.csdn.net/ligang2585116‘//‘http://blog\\.csdn\\.net/ligang2585116‘
V. Expansion of numerical values

ES6 a partial numerical operation to the number object, and gradually reduces the global method to make the language modular. And the Math object is extended in relation to it.

Binary and octal notation

ES6 provides a new notation for binary and octal values, respectively, with the prefix 0b and 0o (which is no longer allowed with prefix 0).

0503// true0503// true
Method
Method Description
Number.isfinite () Checks if a value is a finite
Number.isnan () Checks if a value is Nan
Number.parseint () Convert to Integer
Number.parsefloat () Convert to floating point
Number.isinteger () Determines whether a value is an integer

Example:

/* isfinite () */ Number. Isfinite ( the);//True Number. Isfinite (Infinity);//False Number. Isfinite ("5");//Falseisfinite("5");//True/* IsNaN () */ Number. IsNaN (NaN);//True Number. IsNaN (5);//False Number. IsNaN ("NaN");//FalseIsNaN("NaN");//True/* parsefloat () */ Number. parseint ("12.01a");//parseint("12.01a");///* parsefloat () */ Number. parsefloat ("12.01a");//12.01parsefloat("12.01a");//12.01/* Isinteger () */ Number. Isinteger (121);//True Number. Isinteger (121.0);//True Number. Isinteger (121.01);//False Number. Isinteger ("121");//False

Attention:

    • isFinite()isNaN()the difference is that the traditional method calls number () to convert a non-numeric value to a value, and the two new methods are valid only for numeric values, and non-numeric values return FALSE.

      window.isNaN("abc"// trueNumber.isNaN("abc"// false
    • Number.parseInt(), and Number.parseFloat() migrated to the number object, the behavior remains exactly the same.

Math extension

(1) Math.trunc (): Removes the fractional part of a number and returns the integer portion;
(2) Math.sign (): Determine whether a number is positive, negative, or zero.

Example: Math extension

/* TRUNC () */Math. Trunc (12.001);//Math. Trunc ("12.001");///* SIGN () */Math. sign (123);//1Math. sign ("123");//1Math. sign (-123);//-1Math. sign (0);//0Math. sign (-0);//-0Math. sign ("12s");//NaN
Vi. expansion of arrays convert class arrays and traversed objects to real arrays
Array.from(document.querySelectorAll(‘p‘));Array.from(arguments);
Convert a set of numbers to an array
Array.of(1,2,3);
Returns the first array member that matches a condition
[151015].find(function(value, index, arr) {    return9// 10
Returns the position of the first qualified array member
[151015].findIndex(function(value, index, arr) {    return9// 2
Array padding
[‘a‘‘b‘‘c‘].fill(7);// [7, 7, 7]newArray(3).fill(7);   // [7, 7, 7][‘a‘‘b‘‘c‘].fill(712// [‘a‘, 7, ‘c‘]
Array traversal
for (let index of [‘a‘‘b‘].keys()) {}for (let elem of [‘a‘‘b‘].values()) {}for (let [index, elem] of [‘a‘‘b‘].entries()) {}
Whether the array contains the given value
[123].includes(2);  // true[123].includes(33// false[123].includes(3, -1);// true

es6--extension of string, regular, numeric, array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.