当前位置:网站首页>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 .

  1. Objects have properties and methods Complex data types have properties and methods
  2. Why simple data types have lenght Attribute? ?
  3. 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 .

  1. When you give str When you assign , Constant ’abc’ Will not be modified , Still in memory
  2. Reassign string , Will re open up space in memory , This feature is the immutability of strings
  3. 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]所创,转载请带上原文链接,感谢