Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ String JavaScript type system     - Oracle physical storage structure outline (Database)

- Java, hashcode, equals and == (Programming)

- OpenGL Superb Learning Notes - Fragment Shader (Programming)

- Linux, modify / retrieve the root password (Linux)

- Echo Command Examples (Linux)

- Git delete files (Linux)

- Analysis: Little Notebook facing a major security threat secure online (Linux)

- Linux alpine use the command line to access Gmail (Linux)

- How to enhance the security of Linux systems (Linux)

- Tomcat installation under Linux (Server)

- Manually create Oracle Database Explanations (Database)

- Virtual Judge environment to build and configure under Ubuntu (Server)

- Mumble installation source VoIP application on Ubuntu (Linux)

- Change the kernel boot sequence after CentOS 7 kernel upgrade (Linux)

- Android Service Lifecycle and usage (Programming)

- Mahout source code analysis: FP-Growth algorithm parallelization (Programming)

- Shell Programming points to note about the function (Programming)

- Detailed software to run UnixBench (Linux)

- Ubuntu 14.10 / 14.04 / 12.04 virtual users to install the printing software Boomaga (Linux)

- Packages with Snort intrusion monitoring light (Linux)

 
         
  String JavaScript type system
     
  Add Date : 2018-11-21      
         
         
         
  In front of the words
 
string is a single or double quotes sequences of characters, and is defined between the same kind of quotation marks, which must be in pairs of single or double quotation marks. Unique string that it is not the only type of fixed size original

Each character in the string has a specific location, from the first character position 0, the second character in position 1, and so on, the last character position of this means that the string must be the length of the string minus 1

Feature
 
 The JavaScript strings are immutable. String concatenation need to create a new string, then the string needs two splicing fill in the new string, and finally the destruction of the original string. This process occurs in the background, but also in some older browsers (IE6) string concatenation slow reason, but then have solved the problem of low efficiency.

var lang = "java";
lang = lang + "script";

Escape character
 
 Also known as the escape character character literal

\ 0 null bytes
\ N newline
\ T Tab
\ B space
\ R carriage return
\ F feed
\\ Slash
\' apostrophe
\" Double quotes
\ Xnn nn is a hexadecimal character (n is 0-f), such as \ x41 represents 'A'
\ Unnnn hexadecimal nnnn represents a Unicode character (n is 0-f), such as \ u03a3 represent Greek characters

When the string contains quotation marks, there are three solutions

[1] single quotes embedded in double quotes

[2] double quotes embedded single quotation mark

[3] use the escape character "\"

console.log ( ' "test"'); // "test"
console.log ( " 'test'"); // 'test'
console.log ( '\' test \ ''); // 'test'

Inherited Methods
 
 String type is a character string corresponding to the type of packaging, inherited the general method reference type

valueOf (), toString () and toLocaleString (): Returns a string representation

console.log ( "test" .valueOf ()); // "test"
console.log ( "test" .toString ()); // "test"
console.log ( "test" .toLocaleString ()); // "test"

length property
 
Each instance of type String has a length attribute indicates the number of characters

[Note] This property can only be read, can not be changed

var str = "test";
console.log (str.length); // 4
str.length = 6;
console.log (str, str.length); // "test", 4

String () method
 
Conversion rules String () method is:

[1] If the values are toString () method, then calling the method (no arguments) and returns the corresponding results

[2] null and undefined not toString () method returns null and undefined

console.log (undefined.toString ()) // error
console.log (null.toString ()) // error
console.log (String (undefined)); // 'undefined'
console.log (String (null)); // 'null'
console.log (String (true), String (false)); // 'true' 'false'
console.log (String (10.1)); // 10.1
console.log (String ({})); // [object Ojbect]

[Note] To use a value to a string, you can use the + operator it with an empty string '' together

console.log (typeof (1 + ''), (1 + '')); // string '1'
console.log (typeof (undefined + ''), (undefined + '')); // string 'undefined'
console.log (typeof (null + ''), (null + '')); // string 'null'
console.log (typeof (true + ''), (true + '')); // string 'true'
console.log (typeof ({} + ''), ({} + '')); // string '[object Object]'

Character access method
 
 Receiving a parameter-based character position 0, in the form of single-character string is returned

charAt (): Returns the position of character

[Note] When the parameter is empty, the default parameter is 0; when the parameter is out of range, then nothing output

var str = "hello";
console.log (str.charAt (1)); // e
console.log (str.charAt (-1)); // empty
console.log (str.charAt (10)); // empty
console.log (str.charAt ()); // h

Brackets plus a numerical index (ES5): Returns the character at that position (IE7- does not support output undefined)

[Note] When the parameters are out of range, the output undefined; when the parameter is empty, an error

var str = "hello";
console.log (str [1]); // e
console.log (str [-1]); // undefined
console.log (str [10]); // undefined
console.log (str []); // error

charCodeAt (): Returns the position of character encoding, character encoding type Number

    [Note] When the parameter is empty, the default parameter is 0; when the parameter is out of range, the output is NaN

var str = "hello";
console.log (str.charCodeAt (1)); // 101
console.log (str.charCodeAt (-1)); // NaN
console.log (str.charCodeAt (10)); // NaN
console.log (str.charCodeAt ()); // 104

String.fromCharCode (): the transfer of one or more encoded value into a string (static method)

    [Note] parameters in the range of ASCII table

var stringValue = 'hello';
console.log (stringValue.charAt (1)); // 'e'
console.log (stringValue.charCodeAt (1)); // 101
console.log (typeof stringValue.charCodeAt (1)); // 'number'
console.log (String.fromCharCode (104,101,108,108,111)); // 'hello'
console.log (String.fromCharCode (0x6211,0x662f, 0x5c0f, 0x706b, 0x67f4)); // 'I'm a little match'
console.log (stringValue [1]); // 'e'

String concatenation
 
concat (): can accept any number of parameters for one or more strings spliced together, and returns the new string concatenation obtained

+: + Operator in most cases easier than concat ()

var stringValue = 'hello';
console.log (stringValue.concat ( 'world',) '!'); // 'hello world!'
console.log (stringValue + 'world' + '!'); // 'hello world!'

Creating strings
 
 Returns a substring of a string operation, without arguments returns the original string. Total substr, subtring and slice three kinds

substr (a, b): a-> substring starting position, b-> substring length (optional, defaults to the original end of the string)

Let the original length of the string is len

[1] When a> = len, not output

[2] When a <0 and | a |
[3] When a <0 and | a |> time = len, output from (0) to (b) the location of

[4] When b <0, b = 0

[5] When b> = the number of characters available to the maximum number of characters output

[Note] IE8- problem processing the first argument is negative at the output of the original string

var stringValue = 'hello world';
console.log (stringValue.substr ()); // 'hello world'
console.log (stringValue.substr (2)); // 'llo world'
console.log (stringValue.substr (20)); // empty
console.log (stringValue.substr (-2,3)); // 'ld'
console.log (stringValue.substr (-2,20)); // 'ld'
console.log (stringValue.substr (-20,2)); // 'he'
console.log (stringValue.substr (-20, -2)); // empty
console.log (stringValue.substr (2,5)); // llo w

substring (a, b): a-> substring starting position, b-> after the end of a substring position (optional, defaults to the original length of the string)

Let the original length of the string is len

[1] When a <0, a = 0; when b <0, b = 0

[2] When a> b> 0 Shi, substring (b, a)

[3] When a> = len, no output

[4] When b> = len, the maximum number of characters output

var stringValue = 'hello world';
console.log (stringValue.substring ()); // 'hello world'
console.log (stringValue.substring (2)); // 'llo world'
console.log (stringValue.substring (20)); // empty
console.log (stringValue.substring (-2,2)); // 'he'
console.log (stringValue.substring (-2,20)); // 'hello world'
console.log (stringValue.substring (3,2)); // 'l'
console.log (stringValue.substring (-20,2)); // 'he'
console.log (stringValue.substring (-20, -2)); // empty

slice (a, b): a-> substring starting position, b-> after the end of a substring position (optional, defaults to the original length of the string)

Let the original length of the string is len

[1] When a> = len, not output

[2] When a <0 and | a |
[3] When a <0 and | a |> time = len, output from (0) to (b) the location of

[4] When b> = len, equivalent to no b

[5] When b <0 and | b |
[6] When b <0 and | b |> time = len, not output

[7] When a> b> 0, no output

var stringValue = 'hello world';
console.log (stringValue.slice ()); // 'hello world'
console.log (stringValue.slice (2)); // 'llo world'
console.log (stringValue.slice (2, -5)); // 'll0'
console.log (stringValue.slice (2, -20)); // empty
console.log (stringValue.slice (20)); // empty
console.log (stringValue.slice (-2,2)); // empty
console.log (stringValue.slice (-2, -20)); // empty
console.log (stringValue.slice (-2,20)); // 'ld'
console.log (stringValue.slice (-20,2)); // 'he'
console.log (stringValue.slice (-20, -2)); // 'hello wor'

Position of the string
 
There are two Find substring from a string method indexOf () and lastIndexOf (). Both methods accept two parameters: the substring to look for and find the index indicates the starting position (optional). Substring returns the first position in the string condition is satisfied, if not found returns -1 (location method does not affect the original string)

[Note] The return value is of type Number

indexOf (): from left to right search

lastIndexOf (): right to left search

var string = 'hello world world';
console.log (string.indexOf ( 'ld', 10)); // 15
console.log (string.lastIndexOf ( 'ld', 10)); // 9

[Tips] find out a string of all eligible substring

function allIndexOf (str, value) {
    var result = [];
    var pos = str.indexOf (value);
    while (pos> -1) {
        result.push (pos);
        pos = str.indexOf (value, pos + value.length);
    }
    return result;
}
console.log (allIndexOf ( 'helllhelllhelll', 'll')); // [2,7,12]

Case conversion
 
toUpperCase (): all converted to uppercase

toLowerCase (): convert all lowercase

toLocaleUpperCase (): all converted to uppercase (for the region)

toLocaleLowerCase (): convert all lowercase (for the region)

[Note] without knowing your code will run in which language environment, the use of a more robust method for the region

var string = 'Hello World';
console.log (string.toLowerCase ()); // hello world
console.log (string.toLocaleLowerCase ()); // hello world
console.log (string.toUpperCase ()); // HELLO WORLD
console.log (string.toLocaleUpperCase ()); // HELLO WORLD

[Note] case conversion methods can be used continuously

console.log (. (string.toUpperCase ()) toLowerCase ()); // hello world

String comparison
 
localeCompare (): used to compare two strings if the string in the alphabet should be ranked before the string argument, it returns a negative number (in most cases -1); If the string is equal to the string parameter, return 0; if after, it returns a positive number (in most cases 1)

[Note] in the ASCII table, capital letters before lowercase letters

var stringValue = 'yellow';
console.log (stringValue.localeCompare ( 'brick')); // 1 'y'> 'b'
console.log (stringValue.localeCompare ( 'yellow')); // 0 'yellow' == 'yellow'
console.log (stringValue.localeCompare ( 'zoo')); // - 1 'yellow' < 'zoo'

Pattern Matching
 
 String type defines several methods for string matching pattern. Pattern matching content related to regular expressions, details to this venue

match ()

Only accepts one parameter, a string or a regular, save the contents to match returns an array

[Note] When coupled with the global mark, match () method does not return value and input attribute index

[1] without / g

var string = 'cat, bat, sat, fat';
var pattern = /.at/;
var matches = string.match (pattern);
console.log (matches, matches.index, matches.input); // [ 'cat'] 0 'cat, bat, sat, fat'

[2] plus / g

var string = 'cat, bat, sat, fat';
var pattern = /.at/g;
var matches = string.match (pattern);
console.log (matches, matches.index, matches.input); // [ 'cat', 'bat', 'sat', 'fat'] undefined undefined

[3] String

var string = 'cat, bat, sat, fat';
var pattern = 'at';
var matches = string.match (pattern);
console.log (matches, matches.index, matches.input); // [ 'at'] 1 'cat, bat, sat, fat'

search ()

Only accepts one parameter, a string or a regular return to the position in the string matches the contents of the first occurrence, similar to the starting position can not be set indexOf, find returns -1

[1] Regular (plus / g and without / g the same effect)

var string = 'cat, bat, sat, fat';
var pattern = /.at/;
var pos = string.search (pattern);
console.log (pos); // 0

[2] String

var string = 'cat, bat, sat, fat';
var pattern = 'at';
var pos = string.search (pattern);
console.log (pos); // 1

[Tips] to locate all matches

function fnAllSearch (str, pattern) {
    var pos = str.search (pattern);
    var length = str.match (pattern) [0] .length;
    var index = pos + length;
    var result = [];
    var last = index;
    result.push (pos);
    while (true) {
        str = str.substr (index);
        pos = str.search (pattern);
        if (pos === -1) {
            break;
        }
        length = str.match (pattern) [0] .length;
        index = pos + length;
        result.push (last + pos);
        last + = index;
    }
    return result;
}
console.log (fnAllSearch ( 'cat23fbat246565sa3dftf44at', / \ d + /)); // [3,9,17,22]

replace ()

This method accepts two parameters: the first is a regular expression or a string (to be looking for), and the second is a string or a function (replace the contents of)

[1] string replacement

var string = 'cat, bat, sat, fat';
var result = string.replace ( 'at', 'ond');
console.log (result); // 'cond, bat, sat, fat'

[2] no n / g to replace

var string = 'cat, bat, sat, fat';
var result = string.replace (/ at /, 'ond');
console.log (result); // 'cond, bat, sat, fat'

[3] There are regular / g replacement

var string = 'cat, bat, sat, fat';
var result = string.replace (/ at / g, 'ond');
console.log (result); // 'cond, bond, sond, fond'

[4] function replaces

In the case of only one match (that match the pattern string is passed to this function three parameters: match pattern, pattern matching position of the item in the string, the original string expressions defined in the positive. the case of multiple capturing groups, the parameters passed to the function followed by a match pattern, matches the first capture group matches matches the second capturing group ...... N-th capturing group, but the last two parameters are still matches the pattern in the string location and the original string, the function returns a string

var string = 'cat, bat, sat, fat';
var index = 0;
var result = string.replace (/ at / g, function (match, pos, originalText) {
    index ++;
    if (index == 2) {
        return 'wow';
    } Else {
        return '0';
    }
});
console.log (result); // 'c0, bwow, s0, f0'

[Tips] prevent cross-site scripting attacks xss (css)

function htmlEscape (text) {
    return text.replace (/ [<> "&] / g, function (match, pos, originalText) {
        switch (match) {
            case '<':
            return '& lt;';
            case '>':
            return '& gt;';
            case '&':
            return '& amp;';
            case '\ "':
            return '& quot;';
        }
    });
}
console.log (htmlEscape ( '

Hello world !'));
// & Lt; p class = & quot; greeting & quot; & gt; Hello world & lt;! / P & gt;
console.log (htmlEscape ( '

Hello world !'));
// Ibid.

split ()

This method can be based on a specified delimiter string is divided into a plurality of strings, and the results in an array, separator can be a string, it can be a RegExp. This method can accept a second parameter (optional) specifies the size of the array, and if the second argument is a value in the range 0-array.length output in accordance with the specified parameters, all other cases, the results are output

[Note] IE8- opposite the split () in the expression ignores capture group

[Tips] If it is split ( ''), the original array is a character that came out after split

var colorText = 'red, blue, green, yellow';
console.log (colorText.split ( '')); // [ "r", "e", "d", ",", "b", "l", "u", "e", ", "," g "," r "," e "," e "," n ",", "," y "," e "," l "," l "," o "," w "]
console.log (colorText.split ( ',')); // [ "red", "blue", "green", "yellow"]
console.log (colorText.split ( ',', 2)); // [ "red", "blue"]
console.log (colorText.split (/ \, /)); // [ "red", "blue", "green", "yellow"]
console.log (colorText.split (/ e /)); // [ "r", "d, blu", ", gr", "", "n, y", "llow"]
console.log (colorText.split (/ [^ \,] + /)); // will remove the string into a delimiter other than a comma [ "", "", "", "", "" ], IE8- would recognize as [ ",", ",", ","]

trim () (ECMAScript5)
 
Remove trailing blanks and return to the pre-copy string

var string = 'hello world';
console.log (string.trim ()); // 'hello world';

[Tips1] can trim () to determine whether the null character input

if (usename.trim (). length) {
    alert ( 'correct');
} Else {
      alert ( 'error');
}

[Tips2] with a regular analog trim ()

function fnTrim (str) {
    return str.replace (/ ^ \ s + | \ s + $ /, '')
}
console.log (fnTrim ( 'hello world')); // 'hello world'

     
         
         
         
  More:      
 
- Use the command line MySQL database backup and recovery (Database)
- Using IntelliJ IDEA 13 integrated development environment to build Android (Linux)
- Ubuntu 14.04 and derivative version of the user on how to install cURL 7.37.1 (Linux)
- Type Linux commands (Linux)
- Ubuntu users to install Xtreme Download Manager (Linux)
- Ubuntu 14.04 LTS compiler installation R Source Code (Linux)
- Ubuntu 14.10 installation SecureCRT 7.3 (Linux)
- How to clean up your Ubuntu 14.10 / 14.04 / 13.10 system (Linux)
- SELinux security permissions HTTP + PHP service changes (Server)
- CentOS7 build GlusterFS (Linux)
- Oracle 11g users to create, authorize and import dmp file (Database)
- Linux use iptables ban Ping (Linux)
- Java open source monitoring platform Zorka basic use (Linux)
- Linux server Php injection prevention (Linux)
- TCP protocol flaw incomplete records (Linux)
- The security configuration of Linux (Linux)
- Ubuntu Apache virtual host configuration (Server)
- 4 lvcreate example commonly used commands (Linux)
- pkg-config to use (Linux)
- Use netcat [nc] command on Linux and Unix port scan (Server)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.