Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Properties and methods of the String type

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

Attribute

Each instance of the string String type has a length property that represents the number of characters in the string. Since the string is immutable, the length of the string is also immutable

The length property of a string is not enumerated in a for/in loop and cannot be deleted by the delete operator

[note] for the string s, the index of the last character is s.length-1

Var str = "test"; console.log (str.length); / / 4str.length = 6 console.log (str,str.length); / / "test", 4 instance methods

There are more than 20 instance methods of string String object, including three common object methods inherited by toString (), toLocaleString () and valueOf () from Object object, four access character methods of chartAt (), bracket [], charCodeAt () and fromCharCode (), two string concatenation methods of concat () and plus sign +, and three substring creation methods of slice (), substr () and substring (). ToLowerCase (), toLocaleLowerCase (), toUpperCase (), toLocaleUpperCase (), indexOf () and lastIndexOf (), match (), search (), replace (), split (), trim () and localeCompare ().

Object general method

The String type is the wrapper type corresponding to the string, which inherits the three general methods of Object object: toString (), toLocaleString () and valueOf ().

[toString ()]

The toString () method returns the original string value of string

[toLocaleString ()]

The toLocaleString () method returns the original string value of string

[valueOf ()]

The valueOf () method returns the original string value of string

Console.log ("test" .valueof ()); / / "test" console.log ("test" .toString ()); / / "test" console.log ("test" .toLocaleString ()); / / "test" access character method

There are four methods to access character strings: chartAt (), bracket [], charCodeAt () and fromCharCode ().

[chartAt ()]

The charAt () method takes a parameter based on the character position of 0 and returns the character at the specified position. The default parameter is 0 when the parameter is empty or NaN, and an empty string is returned when the parameter is out of range

Var str = "hello"; console.log (str.charAt (1)); / / econsole.log (str.charAt (- 1)); / /''console.log (str.charAt (10)); / /' console.log (str.charAt ()); / / h console.log (str.charAt (NaN)); / / h

The charAt () method involves implicit type conversion of the Number () function. If converted to a numeric value, the string is output according to the above rules; if converted to NaN, the 0th character is output.

Var str = "hello"; console.log (str.charAt (true)); / / 'e'console.log (str.charAt (false)); / /' h'console.log (str.charAt ('abc')); / /' h'console.log (str.charAt ({})); / / 'h'console.log (str.charAt ([2])); / /' l'

[note] the result of x.charAt (pos) is equal to that of x.substring (pos,pos+1), x.substr (pos,1) and x.slice (pos,pos+1).

Var str = "hello"; console.log (str.charAt (1)); / / 'e'console.log (str.substring (1)); / /' e'console.log (str.slice (1)); / / 'e'console.log (str.substr (1)); / /' e'

[brackets]

ECMAScript5 defines another way to access characters, using square brackets plus a numeric index to access specific characters in a string. If the parameter is out of range or NaN, the output undefined; will report an error when there are no parameters; this method does not have the implicit type conversion of the Number () transformation function, but can be converted to a numeric value when the parameter is a single-valued array

[note] IE7- browsers do not support

Var str = "hello"; console.log (str [0]); / / hconsole.log (str`1`); / / econsole.log (str`1`); / / undefinedconsole.log (str [- 1]); / / undefinedconsole.log (strnan]); / / undefinedconsole.log (str []); / / error report

[charCodeAt ()]

The charCodeAt () method, similar to the charAt () method, takes an argument based on the character position of 0, but returns a 16-bit Unicode encoding of the character at the specified position. The return value is a 16-bit integer between 0 and 65535, that is, between 0x0000 and 0xffff

The default parameter is 0 when the parameter is empty or NaN, and NaN is returned when the parameter is out of range

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

Similarly, the charCodeAt () method involves implicit type conversion of the Number () function. If converted to a numeric value, the corresponding value is output according to the above rules; if converted to NaN, the character encoding of the 0th character is output.

Var str = "hello"; console.log (str.charCodeAt (true)); / / 101console.log (str.charCodeAt (false)); / / 104console.log (str.charCodeAt ('abc')); / / 104console.log (str.charCodeAt ({})); / / 104console.log (str.charCodeAt ([2])); / / 08

[fromCharCode ()]

The String constructor itself has a static method: fromCharCode (). The task of this method is to receive one or more character encodings and then convert them into a string. In essence, this method does the opposite of the instance method charCodeAt (). If the parameter is empty or NaN, an empty string is returned. If the parameter exceeds the range of 0-65535, the output character is uncontrollable.

Console.log (String.fromCharCode (104101108108111)); / 'hello'console.log (String.fromCharCode (0x6211) 0x662f); / /' I am a match 'console.log (String.fromCharCode ()); / /' console.log (String.fromCharCode (NaN)); / / 'console.log (String.fromCharCode (- 1)); console.log (String.fromCharCode (65560))

If a character occupies four bytes, it needs to be split into two characters.

Console.log (String.fromCharCode (0xD842, 0xDFB7)); / / "string concatenation

On two methods of string concatenation: common concat () and plus sign +

[concat ()]

The concat () method is used to concatenate one or more strings and return the new string without changing the original string. If the parameter (except the first parameter) is not a string, it is implicitly converted to a string by the String () method, and then the string is concatenated

Var stringValue = 'hello'; var result = stringValue.concat (' Worldwide Magazine console.log (stringValue)); console.log (result); / / 'hello worldview console.log (stringValue); / /' hello'

[note] the first parameter can only be a string, and an error is reported if it is of another type (except an array)

(1) .concat ('2'); / / error (true) .concat ('false'); / / error ({}). Concat (' abc'); / / error report

[note] because there is also a concat () method in the array, the parameter determines how to convert it according to whether the first parameter is an array or a string

/ / '1recorder 2, 3 recollection, concat ([4p5]); / /' 1mage2, 3, 4, 4, 5'[1, 2, 3]. Concat (', 4, 5'); / / [1, 2, 5 "]

[plus sign operator (+)]

Although concat () is a special method for concatenating strings, the plus operator (+) is more often used in practice. Using the plus operator is simpler and more convenient than concat () in many cases.

Var stringValue = 'hello'; console.log (stringValue.concat ('WorldCraft grammatical console.log (stringValue +' world' +'!')); / / 'hello worldview'

[note] string concatenation occurs when one of the operands is a string, or when the object is converted to a string

1 + 2 return racer 3'+ 2 incandra 3'+ 2 incandra; o + 2 helplash 3 = {valueOf:function () {return 1;}}; o + 2 helplash 3

Create a substring

There are three methods to create substrings: slice (), substr () and substring ().

[slice ()]

The slice (start,end) method takes two parameters, start and end, to return a substring of the string from the character of the start position to (but not including) the character of the end position, or all characters from the start position to the end of the string if end is undefined or does not exist

If start is negative, then start = max (length + start,0)

If end is negative, then end = max (length + end,0)

Start and end cannot swap locations

Var stringValue = 'hello world';console.log (stringValue.slice ()); / /' hello world'console.log (stringValue.slice (2)); / / 'llo world'console.log (stringValue.slice (2) undefined); / /' llo world'console.log (stringValue.slice (2 lemon 5)); / / 'llo' console.log (stringValue.slice (2 lemon 20)); / /''console.log (stringValue.slice (20)); / /' 'console.log (stringValue.slice (- 2)) / /''console.log (stringValue.slice (- 2)); / /' 'console.log (stringValue.slice (- 2)); / /' ld'console.log (stringValue.slice (- 20)); / / 'he'console.log (stringValue.slice (- 20)); / /' hello wor'

The slice () method involves implicit type conversion of the Number () transformation function, which is equivalent to start = 0 when start is converted to NaN, and an empty string is output when end is converted to NaN (except when end is undefined).

Var stringValue = 'hello world';console.log (stringValue.slice (NaN)); / /' hello world'console.log (stringValue.slice (0MagneNan)); / /''console.log (stringValue.slice (true, [3])); / /' el'console.log (stringValue.slice (null,undefined)); / / 'hello world'console.log (stringValue.slice ({})); / /' hello world'console.log (stringValue.slice ('2percent, [5])); / /' llo'

[substring ()]

The substring (start,end) method takes two parameters, start and end, to return a substring of the string from the character of the start position to (but not including) the character of the end position, or all characters from the start position to the end of the string if end is undefined or does not exist

If any parameter is NaN or negative, it is replaced by 0

If any parameter is greater than the string length, it is replaced by the string length

If start is greater than end, swap their values

Var stringValue = 'hello world';console.log (stringValue.substring ()); / /' hello world'console.log (stringValue.substring (2)); / / 'llo world'console.log (stringValue.substring (2) undefined); / /' llo world'console.log (stringValue.substring (20)); / / 'console.log (stringValue.substring (- 2 NaN,2)); / /' he'console.log (stringValue.substring (NaN,2)); / / 'he'console.log (stringValue.substring (- 2 Magneto 20)) / / 'hello world'console.log (stringValue.substring (3Magne2)); / /' l'console.log (stringValue.substring (3Magin2)); / / 'hel'console.log (stringValue.substring (- 20Lay 2)); / /' he'console.log (stringValue.substring (- 20LMAV2)); / /''

Similarly, the substring () method also involves implicit type conversion of the Number () transformation function.

Var stringValue = 'hello world';console.log (stringValue.substring (true, [3])); / /' el'console.log (stringValue.substring (null,undefined)); / / 'hello world'console.log (stringValue.substring ({})); / /' hello world'console.log (stringValue.substring ('2percent, [5])); / /' llo'

[substr ()]

The substr (start,end) method requires two parameters, start and end,end, to represent the number of characters returned from the substring; the method returns a substring of end characters starting from the character at the start position in the string; if end is undefined or does not exist, all characters from the start position to the end of the string are returned

If start is negative, then start = max (length + start,0)

If start is NaN, it is equivalent to start = 0

If end is negative or NaN, then end = 0, so an empty string is returned

Start and end cannot swap locations

[note] this method is not ECMAScript standard and has been deprecated

[note] the IE8- browser has a problem passing a negative value to substr (). It returns the original string.

Var stringValue = 'hello world';console.log (stringValue.substr ()); / /' hello world'console.log (stringValue.substr (2)); / / 'llo world'console.log (stringValue.substr (2jue undefined)); / /' llo world'console.log (stringValue.substr (2jinnan)); / / 'console.log (stringValue.substr (NaN,2)); / /' he'console.log (stringValue.substr (20)); / / 'console.log (stringValue.substr (- 2Power3)) / / 'ld'console.log (stringValue.substr (- 2)); / /' ld'console.log (stringValue.substr (- 20)); / / 'he'console.log (stringValue.substr (- 20)); / /' 'console.log (stringValue.substr (- 2)); / / llo w

Similarly, the substr () method also involves implicit type conversion of the Number () transformation function.

Var stringValue = 'hello world';console.log (stringValue.substr (true, [3])); / /' el'console.log (stringValue.substr (null,undefined)); / / 'hello world'console.log (stringValue.substr ({})); / /' hello world'console.log (stringValue.substr ('2percent, [5])); / /' llo w'

[note] for the above three methods of creating substrings, if it is an empty string, it still returns an empty string regardless of the parameter

Var str ='; console.log (str.slice (1)); / /''console.log (str.substring (1)); / /' 'console.log (str.substr (1)); / /' 'case conversion

There are four methods involved in string case conversion in ECMAScript: toLowerCase (), toLocaleLowerCase (), toUpperCase (), toLocaleUpperCase ()

ToLowerCase () and toUpperCase () are two classical methods, borrowed from the method of the same name in java.lang.String. On the other hand, the toLocaleLowerCase () and toLocaleUpperCase () methods are implemented for specific locals. for some regions, the locale-specific method is the same as its general method, but a few languages (such as Turkish) will apply special rules for Unicode case conversion, so the region-specific method must be used to ensure the correct conversion.

[toUpperCase ()]

The toUpperCase () method converts a string to uppercase

[toLowerCase ()]

The toLowerCase () method converts a string to lowercase

[toLocaleUpperCase ()]

The toLocaleUpperCase () method converts a string to uppercase (for region)

[toLocaleLowerCase ()]

The toLocaleLowerCase () method converts the string to lowercase (for region)

[note] it is safer to use a locale-specific approach when you don't know in which locale your code will run

Var string = 'Hello World';console.log (string.toLowerCase ()); / / hello worldconsole.log (string.toLocaleLowerCase ()); / / hello worldconsole.log (string.toUpperCase ()); / / HELLO WORLDconsole.log (string.toLocaleUpperCase ()); / / HELLO WORLD

None of these four methods supports String () implicit type conversion, but only string types.

(true) .toLowerCase (); / report an error (2) .toLocaleLowerCase (); / report an error ({}) .toUpperCase (); / / report an error ([]) .toLocaleUpperCase (); / / report an error

[note] the case conversion method can be used continuously

Var string = 'Hello World';console.log ((string.toUpperCase ()). ToLowerCase ()); / / hello world

Convert a delimited string to the form of a hump

Var txt = "border-top-left"; var arr = txt.split ('-'); for (var I = 1; I

< arr.length; i++){ arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);}var result = arr.join('');console.log(result);//'borderTopLeft" 查找子串位置   有两个从字符串中查找子字符串位置的方法:indexOf()和lastIndexOf()。查找子串位置的方法同访问字符方法charAt()和中括号[]方法有相反的地方,一个通过字符串查找位置,一个则是通过位置查找字符 【indexOf()】   indexOf(searchString,start)方法接收searchString和start两个参数,返回searchString首次出现的位置,如果没有找到则返回-1   该方法会隐式调用String()转型函数,将searchString非字符串值转换为字符串;隐式调用Number()转型函数,将start非数字值(undefined除外)转换为数值   searchString表示要搜索的子字符串;start表示该搜索的开始位置,若忽略该参数或该参数为undefined、NaN或负数时,start = 0 var string = 'hello world world';console.log(string.indexOf('ld'));//9console.log(string.indexOf('ld',undefined));//9console.log(string.indexOf('ld',NaN));//9console.log(string.indexOf('ld',-1));//9console.log(string.indexOf('ld',10));//15console.log(string.indexOf('ld',[10]));//15console.log(string.indexOf('true',[10]));//-1console.log(string.indexOf(false,[10]));//-1 【lastIndexOf()】   与indexOf()不同,lastIndexOf()从右向左查找   lastIndexOf(searchString,start)方法接收searchString和start两个参数,返回searchString第一次出现的位置,如果没有找到则返回-1   同样地,该方法会隐式调用String()转型函数,将searchString非字符串值转换为字符串;隐式调用Number()转型函数,将start非数字值(undefined除外)转换为数值   searchString表示要搜索的子字符串;start表示该搜索的开始位置,若忽略该参数或该参数为undefined、NaN时,start = length - 1;若start为负数,start = 0 var string = 'hello world world';console.log(string.lastIndexOf('ld'));//15console.log(string.lastIndexOf('ld',undefined));//15console.log(string.lastIndexOf('ld',NaN));//15console.log(string.lastIndexOf('ld',-1));//-1console.log(string.lastIndexOf('h',-1));//0console.log(string.lastIndexOf('w',undefined));//12console.log(string.lastIndexOf('ld',10));//9console.log(string.lastIndexOf('ld',[10]));//9console.log(string.lastIndexOf('true',[10]));//-1console.log(string.lastIndexOf(false,[10]));//-1   【tips】查找出字符串所有符合条件的子字符串   可以通过循环调用indexOf()或lastIndexOf()来找到所有匹配的子字符串 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')); / / [2mai 7mai 12]

The lastIndexOf () method is often used to get the extension in the URL address

Var url = "http://cnblogs.com/xiaohuochai.txt";function getFileFormat (url) {var pos = url.lastIndexOf ('.'); return url.slice (pos+1);} console.log (getFileFormat (url)); / / 'txt'

Regular matching method

Some regular operations in javascript, such as finding and testing, can be implemented through RegExp methods, while other operations such as segmentation and replacement can be implemented through String class methods.

There are four regular matching methods in String class: match (), search (), replace () and split ().

[match ()]

The match () method accepts only one parameter that is regular or string and returns the matching content as an array. This method is similar to the exec () method of the regular expression RegExp, except that it replaces the RegExp and String objects.

If the match fails, the match () method returns null

'x'.match (/ y /); / / null

[1] if the global flag is not set, the match () method and the exec () method have the same result

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' var matches = string.match (pattern); console.log (matches,matches.index,matches.input); / / [' cat'] 0 'cat,bat,sat,fat' var string =' cat,bat,sat,fat';var pattern = / .at/ Var exec = pattern.exec (string); console.log (exec,exec.index,exec.input); / / ['cat'] 0' cat,bat,sat,fat' var exec = pattern.exec (string); console.log (exec,exec.index,exec.input); / / ['cat'] 0' cat,bat,sat,fat'

[2] after setting the global flag, the exec () method still returns a single match, while the match () method returns an array of strings, including the text that matches successfully each time, but without the index and input attributes

Var string = 'cat,bat,sat,fat';var pattern = / .at / g political var matches = string.match (pattern); console.log (matches,matches.index,matches.input); / / ["cat", "bat", "sat", "fat"] undefined undefined var matches = string.match (pattern); console.log (matches,matches.index,matches.input) / ["cat", "bat", "sat", "fat"] undefined undefined var string = 'cat,bat,sat,fat';var pattern = / .at / g politics var exec = pattern.exec (string); console.log (exec,exec.index,exec.input); / / [' cat'] 0 'cat,bat,sat,fat' var exec = pattern.exec (string); console.log (exec,exec.index,exec.input); / / [bat'] 4' cat,bat,sat,fat'

[3] the match () method, as a method of string String, accepts a parameter as a string, and the result is the same as a regular expression that does not set a global flag, returns only the first match, and has index and input attributes

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

When the global flag is not set, both the match () method and the exec () method contain the information to capture the packet; after setting the global flag, the match () method does not contain the information to capture the packet

Var string = 'cat,bat,sat,fat';var pattern = / (.) at/g;var matches = string.match (pattern); console.log (matches); / / [' cat',' bat', 'sat',' fat'] var exec = pattern.exec (string); console.log (exec); / / ['cat','c'] var string =' cat,bat,sat,fat';var pattern = / (.) at/;var matches = string.match (pattern); console.log (matches) / / ['cat','c'] var exec = pattern.exec (string); console.log (exec); / / [' cat','c']

[tips] there are two ways to find all the numbers in a string

[1] use the charAt () method

Var str1 = 'j1h442jg24g234j 3g24j1 adventure array = []; var temp =''; for (var I = 0; I

< str1.length; i++){ var value = parseInt(str1.charAt(i));//如果用Number()将无法排除空格 if(!isNaN(value)){ temp += str1.charAt(i); }else{ if(temp != ''){ array.push(temp); temp = ''; } }}if(temp != ''){ array.push(temp); temp = ''; }console.log(array);//["1", "342", "24", "234", "3", "24", "1"]   【2】用match()方法 var str1 = 'j1h442jg24g234j 3g24j1';array = str1.match(/\d+/g);console.log(array);//["1", "342", "24", "234", "3", "24", "1"] 【search()】   search()方法接受一个正则或字符串的参数,返回匹配的内容在字符串中首次出现的位置,类似于不能设置起始位置的indexOf,找不到返回-1   [注意]search()方法不执行全局匹配,忽略全局标志g,也会忽略RegExp对象的lastIndex属性,总是从字符串的开始位置开始搜索 'x'.search(/y/);//-1 var string = 'cat,bat,sat,fat';var pattern = /.at/;var pos = string.search(pattern);console.log(pos);//0var string = 'cat,bat,sat,fat';var pattern = /.at/g;var pos = string.search(pattern);console.log(pos);//0var string = 'cat,bat,sat,fat';var pattern = 'at';var pos = string.search(pattern);console.log(pos);//1   【tips】找出匹配的所有位置 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()】   replace()方法用于替换一个或多个子字符串。它接收两个参数:第一个是正则表达式或字符串,表示待查找的内容;第二个是字符串或函数,表示替换内容。返回替换后的字符串   【1】字符串替换,只能替换第一个子字符串 var string = 'cat,bat,sat,fat';var result = string.replace('at','ond');console.log(result);//'cond,bat,sat,fat'   【2】不设置全局标志g,也只能替换第一个子字符串 var string = 'cat,bat,sat,fat';var result = string.replace(/at/,'ond');console.log(result);//'cond,bat,sat,fat'   【3】设置全局标志g,替换所有匹配的子字符串 var string = 'cat,bat,sat,fat';var result = string.replace(/at/g,'ond');console.log(result);//'cond,bond,sond,fond'   与match()和seartch()方法相比,replace()方法更为强大,它可以在第二个参数中通过短属性名来使用某些正则表达式的静态属性 短属性名 说明$& 最近一次的匹配项$` 匹配项之前的文本$' 匹配项之后的文本$1,$2... 表示第N个匹配捕获组 var string = 'cat-bat-sat-fat';console.log(string.replace(/(.)(at)/g,'$&'));//'cat-bat-sat-fat'console.log(string.replace(/(.)(at)/g,'$`'));//'-cat--cat-bat--cat-bat-sat-'console.log(string.replace(/(.)(at)/g,"$'"));//'-bat-sat-fat--sat-fat--fat-'console.log(string.replace(/(.)(at)/g,'$1'));//'c-b-s-f'console.log(string.replace(/(.)(at)/g,'$2'));//'at-at-at-at' var string = '2016-06-24';console.log(string.replace(/(\d{4})-(\d{2})-(\d{2})/g,'$2/$3/$1'));//'06/24/2016'   replace()方法的第二个参数可以是函数,这样文本的处理更加灵活   如果在只有一个匹配项的情况下,该方法会向这个函数传递3个参数:模式的匹配项、模式匹配项在字符串中的位置、原始字符串 var string = 'cat,bat,sat,fat';var index = 0;var matchArray = [];var posArray = [];var text = '';var result = string.replace(/at/g,function(match,pos,originalText){ matchArray.push(match); posArray.push(pos); text = originalText; index++; if(index % 2){ return 'wow'; }else{ return '0'; }});console.log(matchArray);//["at", "at", "at", "at"]console.log(posArray);//[1, 5, 9, 13]console.log(text);//'cat,bat,sat,fat'console.log(result);//'cwow,b0,swow,f0'   如果正则表达式定义多个捕获组,则该方法传递给函数的参数依次是模式的匹配项、第一个捕获组的匹配项、第二个捕获组的匹配项……第N个捕获组的匹配项,但最后两个参数仍然分别是模式的匹配项在字符串中的位置和原始字符串,这个函数返回一个字符串 var string = 'cat,bat,sat,fat';var index = 0;var matchArray = [];var m1Array = [];var posArray = [];var text = '';var result = string.replace(/(.)at/g,function(match,m1,pos,originalText){ matchArray.push(match); m1Array.push(m1); posArray.push(pos); text = originalText; return m1 + 'ta';});console.log(matchArray);//["cat", "bat", "sat", "fat"]console.log(m1Array);//['c','b','s','f']console.log(posArray);//[1, 5, 9, 13]console.log(text);//'cat,bat,sat,fat'console.log(result);//'cta,bta,sta,fta'   【tips】首字母大写 var text = 'one two three';var result = text.replace(/\b(\w+)\b/g,function(match,m1,pos,originalText){ return m1.charAt(0).toUpperCase()+m1.substring(1); })console.log(result);   【tips】HTML标签转义 function htmlEscape(text){ return text.replace(/["&]/g,function(match,pos,originalText){ switch(match){ case ''; case '&': return '&'; case '\"': return '"'; } });}console.log(htmlEscape('Hello world! '));//Hello world! console.log(htmlEscape('Hello world! '));//同上   【tips】日期格式化 var array = ['2015.7.28','2015-7-28','2015/7/28','2015.7-28','2015-7.28','2015/7---28'];function formatDate(date){ return date.replace(/(\d+)\D+(\d+)\D+(\d+)/,'$1年$2月$3日')}var result = [];for(var i = 0 ; i < array.length; i++){ result.push(formatDate(array[i]));}console.log(result);//["2015年7月28日", "2015年7月28日", "2015年7月28日", "2015年7月28日", "2015年7月28日", "2015年7月28日"]   【tips】找出重复项最多的字符和个数 var str = 'aaaaabbbbbdddddaaaaaaaffffffffffffffffffgggggcccccce';var pattern = /(\w)\1+/g;var maxLength = 0;var maxValue = '';var result = str.replace(pattern,function(match,match2,pos,originalText){ if(match.length >

MaxLength) {maxLength = match.length; maxValue = match2;}}) console.log (maxLength,maxValue); / / 18 "f"

[split ()]

The split () method splits a string into multiple strings based on the specified delimiter and places the result in an array, which can be either a string or a RegExp.

This method can accept the second parameter (optional) to specify the size of the array. If the second parameter is a value within the range of 0-array.length, it will output all the results according to the specified parameter.

If the specified delimiter does not appear in the string, the value of the original string is returned as an array

[note] whether the regular expression in the parameter uses the global flag g has no effect on the result

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 (',', 6)); / / ["red", "blue", "green", "yellow"] console.log (colorText.split ('-')); / [red,blue,green,yellow "] console.log (colorText.split (/\, /)) / / ["red", "blue", "green", "yellow"] console.log (colorText.split (/ e /)); / / ["r", "djiming blu", ", gr", "", "nPerry y", "llow"] console.log (/ [^\,] + /)) / / change strings other than commas to delimiters [","], IE8- will be recognized as [","]

Remove leading and trailing spaces

[trim ()]

ECMAScript5 defines the trim () method for all strings. This method creates a copy of the string, removes all white space characters from the prefix and suffix, and then returns the result

Because the trim () method returns a copy of the string, the prefix and suffix spaces in the original string remain unchanged

[note] IE8- browsers do not support

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

White space characters include not only spaces, but also tabs (\ t), line feeds (\ n) and carriage returns (\ r).

'\ r\ nabc\ t'.trim () / /' abc'

In addition, firefox, safari, and webkit support non-standard trimRight () to delete white space characters at the end of a string

Var string = 'hello world'; console.log (string.trimRight ()); / /' hello world'

[tips] use trim () to determine whether the input character is empty or not

If (usename.trim () .length) {alert ('correct');} else {alert (' error');}

[tips] use regular expressions to simulate trim ()

Function fnTrim (str) {return str.replace (/ ^\ s + |\ console.log (fnTrim ('hello world'))} console.log (/ /' hello world' string comparison)

[localeCompare ()]

The localeCompare () method is used to compare two strings, following these rules

[1] if the string should be listed before the string parameter in the alphabet, a negative number is returned (- 1 in most cases)

[2] if the string is equal to the string parameter, 0 is returned

[3] if the string should be ranked after the string parameter in the alphabet, a positive number is returned (1 in most cases)

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'   [注意]虽然在字母表中大写字母在小写字母的前面,所以大写字母 < 小写字母。但localeCompare()方法会考虑自然语言的排序情况,把'B'排在'a'的后面 console.log('B'.localeCompare('a'));//1console.log('B' >

'a'); / / falseconsole.log (' b'.localeCompare ('a')); / / 1console.log ('b' >'a'); / / true

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report