当前位置:网站首页>JS string - string string object method
JS string - string string object method
2020-11-06 22:11:00 【The front end of the attack】
Ⅰ- one -String String type
One String How to create
- How to create literal quantity , In stack
- Instantiation creation method ,(new) In stack
- How to create constructors , Will create a character object , In the pile
- A string of length Gets the length of the string . It's just readable Do not modify Can only get
- str.charAt(1) Equate to str[1]
// How to create literal quantity
var str="abc",str1='abd',str2=`abc`;
// Instantiation creation method
var str4=String('abc');// In stack
// How to create constructors
var str5=new String('abc');// Character objects , In the pile
console.log(str4===str5);//false
console.log(str4==str5);//true
Two Basic packaging type
To facilitate the operation of basic data types , JavaScript Three special reference types are also provided : String、Number and Boolean.
The basic wrapper type is to wrap a simple data type into a complex data type , So the basic data type has properties and methods .
- Objects have properties and methods Complex data types have properties and methods
- Why simple data types have lenght Attribute? ?
- Basic packaging type : It's wrapping simple data types into complex data types
// Basic packaging type
varstr='andy';
console. log(str .length);
// Objects have properties and methods Complex data types have properties and methods
// Why simple data types have lenght Attribute? ?
// Basic packaging type : It's wrapping simple data types into complex data types
// (1) Wrapping simple data types into complex data types
var temp=new String('andy' );
// (2) Give the value of the temporary variable to str
str = temp;
// (3) Destroy this temporary variable
temp=nul1:
3、 ... and String The immutability of string
It means that the values in it are immutable , Although it seems that the content can be changed , But the address has changed , A new memory space has been opened up in memory .
- When you give str When you assign , Constant ’abc’ Will not be modified , Still in memory
- Reassign string , Will re open up space in memory , This feature is the immutability of strings
- Because of the immutability of string , There are efficiency problems when splicing a large number of strings ;
var str = 'abc' ;
str = 'hello';
// When you give str When you assign , Constant 'abc' Will not be modified , Still in memory
// Reassign string , Will re open up space in memory , This feature is the immutability of strings
// Because of the immutability of string , There are efficiency problems when splicing a large number of strings ;
var str= ‘’;
for(vari=0;i<100000;i++){
str += i;
}
console.log(str); // This result takes a lot of time to show , Because we need to constantly open up new space
Ⅱ - Ii. -String String object method
length Gets the length of the string
let myString = "hello kitty";
myString.length; // Output 11
One Return position according to character
String all methods , Will not modify the string itself ( Strings are immutable ) , The operation will return a new string .
| Method name | explain |
|---|---|
| indexOf( Characters to find , Starting position ) | Returns the location of the specified content in the meta string , If you can't find it, go back -1, The starting position is index Reference no. |
| lastindexOf() | Look backwards , Just find the first match |
1 indexOf
effect : Through the characters , Find the corresponding index and return
grammar :
character string .indexOf( The character you are looking for )
character string .indexOf( The character you are looking for , Which index to start with )
Return value : A number
If there is this character , Then it returns the index of the position of the first character found
If there is no such character , So return -1
let myString = "hello kitty";
myString.indexOf('kitty'); // 6
myString.indexOf('Hello'); //-1
myString.indexOf('hello'); //0
myString.indexOf('hello',3); //-1
//
var str = 'hello world';
// When you look for a character with more than one letter , It will find the position of the first letter that matches and returns
var res = str.indexOf('world');
console.log(res);// The result is 6
2 lastIndexOf()
effect : Through the characters , Find the corresponding index and return , Search back and forth
grammar :
character string .lastIndexOf( The character you are looking for )
character string .lastIndexOf( The character you are looking for , Which index to start with )
Return value : A number
If there is this character , Then it returns the index of the position of the first character found
If there is no such character , So return -1
let myString = "hello kitty";\
myString.lastIndexOf('hello') // 0
myString.lastIndexOf('world') // -1
myString.lastIndexOf('kitty') // 6
myString.lastIndexOf('kitty',3) // -1
//
var str = 'hello world';
// Look from right to left
var res = str.lastIndexOf('l');
console.log(res);// The result is 9
Two Returns the character according to the position
| Method name | explain | Use |
|---|---|---|
| charAt(index) | Returns the character in the specified position (index The index number of the string ) | str.charAt(0) |
| charCodeAt(index) | Gets the... Of the character at the specified location ASCII code (index Reference no. ) | str.charCodeAt(0) |
| str[index] | Gets the character at the specified location | HTML5.IE8. and charAt() equivalent |
1 charAt()
char: character , Represents a character
at: Where is the
effect : Find the corresponding character according to the index and return
grammar : character string .charAt( Indexes )
Return value : The character corresponding to the index position
If there is a corresponding index , So what you get is the character corresponding to the index position
If there is no corresponding index , So what you get is An empty string
var str = 'hello world';
var res = str.charAt(8);
console.log(res);// The result is r , Spaces also occupy the index position
2 charCodeAt() and String.fromCharCode()
charCodeAt()
effect : Find the corresponding character according to the index , Returns the encoding of a character
grammar : character string .charCodeAt( Indexes )
Return value : The character code corresponding to the index position UTF-8 code
String.fromCharCode()
effect : According to the corresponding character , return Unicode Code the corresponding value
grammar :String.fromCharCode( The conversion Unicode code )
Return value : The character code corresponding to the index position UTF-8 code
var str = ' Hello The world ';
// res What you get is you The code of this Chinese character
var res = str.charCodeAt(1);
console.log(res);// The result is 22909 It's the code of this Chinese character
var rek = String.fromCharCode(res); // The encoding is converted to a string
console.log(rek)// The result is good
3、 ... and String operation method ( a key )
| Method name | explain |
|---|---|
| concat(str1,str2,str3…) | concat() Method to connect two or more strings . String concatenation , Equivalent to +, + More commonly used |
| substr(start,length) | from start Position start ( Reference no. ),length Take the number and remember this |
| substring(start, end) | from start Position start , Intercept to end Location ,end There is no basic and slice Same but not negative |
| replace() | Method is used to replace some characters with others in a string , Or replace a substring that matches a regular expression . |
| match() | Method to retrieve the specified value in a string , Or find a match for one or more regular expressions . In an array |
| search() | Used to retrieve the position of a specified substring in a string |
| toUpperCase() | Method to convert a string to uppercase . |
| toLowerCase() | Method to convert a string to lowercase . |
| slice(start, end) | from start Position start , Intercept to end Location , end Can't get ( They're both index numbers ) |
| split() | Cut string Returns an array after cutting Used in object Method join() Array to character contrary |
1 concat()
effect : String concatenation
grammar : character string .concat( The string to be spliced 1, The string to be spliced 2, …)
Return value : A concatenated string
Function and plus (+) It's exactly the same
let myString = "Hello kitty";
//concat()
let str = "aabbcc"
let str2 = " ccddeeff"
myString.concat(str) // "Hello kittyaabbcc"
myString.concat(str,str2) // "Hello kittyaabbcc ccddeeff"
//
var str = 'hello world';
var res = str.concat(' Hello The world ');
console.log(res);// The result is hello world Hello The world
2 substring() and substr()
Parameters do not support negative numbers
subbstring()
effect : Extract some content from the string
grammar : character string .substring( Start index , End index ) - The head is not the tail The second parameter does not write , Default to end
Return value : A new string , The content extracted from the original string
var str2 = 'hello world';
// From the index 1 Start , To the index 7, Index not included 7
var res2 = str2.substring(1, 7);
console.log(res2);// The result is ello w
substr()
effect : Extract some content from the string
grammar : character string .substr( Index started , How many? )
The second parameter does not write , By default, it is calculated according to the end of the string
Return value : A new string , The content extracted from the original string
var str = 'hello world';
// From the index 1 Start , Count back 7 individual , extracted
var res = str.substr(1, 7);
console.log(res);// The result is ello wo
3 split()
effect : According to your needs , Cut string
grammar : character string .split(‘ The characters you want to cut ’)
Parameters cut you according to what you write
If you write a character that is not in the string , So I'll cut you a whole string
If the parameter is not written , It's also about cutting a whole string
If you write a parameter An empty string (""), Will cut you one by one
You can only choose from the back to the front
Return value : It's a Array
Cut each part according to your rules , Put them in the array
let myString = "Hello kitty";
myString.split(""); // ["H", "e", "l", "l", "o", " ", "k", "i", "t", "t", "y"]
myString.split(" "); // ["Hello", "kitty"]
myString.split(" ")[0];//Hello character string Get data with zero subscript
let str2 = "23:34:56:78";
str2.split(":",3) // ["23", "34", "56"]
let str3 = "How,are,you,doing,today?"
str3.split(",") // ["How", "are", "you", "doing", "today?"]
var str = '2020-05-20';
// use - Separate strings , Each segment is placed in the array as a piece of data
var res = str.split('-');
console.log(res);// The result is ["2020", "05", "20"]
4 replace() Method is used to replace some characters with others in a string , Or replace a substring that matches a regular expression .
let myString = "Hello kitty";
myString.replace(/kitty/,"world") // "Hello world"
let name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1"); // "John Doe"
5 match() Method to retrieve the specified value in a string , Or find a match for one or more regular expressions .
let myString = "hello kitty";
myString.match("hello"); //hello
myString.match("Hello"); //null
let str = "2 plus 3 equal 5"
str.match(/\d+/g) //["2", "3", "5"]
6 slice()
slice And an array of slice equivalent
effect : Extract part of the data from a string
grammar :
character string .slice( Start index , End index ) - Not before, not after
character string .slice( Start index , Negtive integer )
When you write negative integers , Express character string .length + Negtive integer
Return value : A string , A part of a string that is extracted from the original string
var str = 'abcdefghijklmn';
// extract str Index in string 1 To the index 10 The characters of , Index not included 10
var res1 = str.slice(1, 10);
// You write -3 Equivalent to str.length + -3 === 11
var res2 = str.slice(1, -3);
var res3 = str.slice(1, 11);
console.log(res1);// The result is bcdefghij
console.log(res2);// The result is bcdefghijk
console.log(res3);// The result is bcdefghijk
7 toUpperCase() 、toLowerCase()
toUpperCase() Method to convert a string to uppercase .
effect : Convert all lowercase letters in a string to uppercase letters
grammar : character string .toUpperCase()
Return value : It's a converted String
var str2 = 'abcdefg';
var res2 = str2.toUpperCase();
console.log(res2);// The result is ABCDEFG
toLowerCase() Method to convert a string to lowercase .
effect : Convert all uppercase letters in a string to lowercase letters
grammar : character string .toLowerCase()
Return value : It's a converted String
var str = 'ABCDEFG';
var res = str.toLowerCase();
console.log(res);// The result is abcdefg
Four Case study
-
split Method can convert a string to an array , You can use the array method
-
conversely join It can also be converted to a string and can be used String method
1 url Intercept
1
function getURLPram(url){
url=url.split("?")[1];
var obj={
};
var arr=url.split("&");
for(var i=0;i<arr.length;i++){
var str=arr[i];
var arr1=str.split("=");
obj[arr1[0]]=arr1[1];
}
return obj;
}
2
function getURLPram(url){
return url.split("?")[1].split("&").reduce(function(value,item){
var arr=item.split("=");
value[arr[0]]=arr[1];
return value;
},{
})
}
var url="https://detail.tmall.com/item.htm?id=570063940353&ali_refid=a3_430406_1007:116401153:J:157145175_0_1069023083
var obj= getURLPram(url);
console.log(obj);
2 String flip
var str="abcdef";
// Convert to array , And then reverse , And then use "" Connect
str=str.split("").reverse().join("");
console.log(str);
版权声明
本文为[The front end of the attack]所创,转载请带上原文链接,感谢
边栏推荐
- All the way, I was forced to talk about C code debugging skills and remote debugging
- Git remote library rollback specified version
- How much disk space does a new empty file take?
- Introduction to the development of small game cloud
- 1万辆!理想汽车召回全部缺陷车:已发生事故97起,亏损将扩大
- 小程序商城系统插件代码该如何写?怎么用代码检查添加插件是否成功?
- C and C / C + + mixed programming series 5 - GC collaboration of memory management
- August 24, 2020: what are small documents? What's wrong with a lot of small files? How to solve many small files? (big data)
- Why is quicksort so fast?
- Metersphere developer's Manual
猜你喜欢

20个XR项目路演,近20个资本机构出席!诚邀您参加2020 Qualcomm XR生态合作伙伴大会

Practice of Xiaoxiong school development board: real equipment access of smart street lamp sandbox experiment

Python basic variable type -- list analysis

#JVM 类加载机制

Utility class functions (continuous update)

How much disk space does a new empty file take?

2020-08-29: process thread differences, in addition to the inclusion relationship, the underlying details?

2020-09-09:裸写算法:两个线程轮流打印数字1-100。

Bluetooth broadcast chip for Shanghai giant micro
![What grammar is it? ]](/img/3b/00bc81122d330c9d59909994e61027.jpg)
What grammar is it? ]
随机推荐
[forward] how to view UserData in Lua
2020-09-09:裸写算法:两个线程轮流打印数字1-100。
Event monitoring problem
Road to simple HTML + JS to achieve the most simple game Tetris
2020-08-15: under what circumstances should data tasks be optimized?
Stickinengine architecture 12 communication protocol
Those who have worked in China for six years and a million annual salary want to share these four points with you
File download manager realized by electron
Google browser realizes video playback acceleration function
Stm32f030c6t6 compatible to replace mm32spin05pf
August 18, 2020: introduce Mr process?
Flink's datasource Trilogy: direct API
谷歌浏览器实现视频播放加速功能
Git remote library rollback specified version
Cloudquery v1.2.0 release
Unexpected element.. required element
2020-08-17:详细说下数据倾斜怎么解决?
Using an example to understand the underlying processing mechanism of JS function
2020-09-03:裸写算法:回形矩阵遍历。
The essence of transaction and the principle of deadlock