Replace string retrieval in js

The replace() method is used to replace characters with other characters

strinObject.replace(regexp/substr,replacement)

regexp/substr a Regexp object specifying the substring or pattern to be replaced

replacement a string value, the replacement text or a function to generate the replacement text

The replace() method of stringObject performs a find and replace operation

return a new string

 

    var str='my name is gf'  
    console.log(str.replace(/gf/, 'gff'))
      
    //my name is gff
 replace all strings

 

 

var r= "1\n2\n3\n";
//replace the letter \n with the semicolon
alert(r.replace(/\n/g, ";"));

Result: 1;2;3; The first parameter of replace can be a regular expression, /g identifies full text matching.
 indexOf:
Returns the character position of the first occurrence of the substring within the String object.
strObj.indexOf(subString[, startIndex])

 

indexOf returns an integer to find the start of a substring in the String object returns -1 if no substring is found

    var str='my name is gf '  
    console.log(str.indexOf('gf') )
    //return 11 spaces to count as a position

 

    var str='my name is Tom '  
      
    console.log(str.indexOf(‘gf') )  
    // -1  

The search() method is used to retrieve a specified substring in a string

    var str='my name is gf '  
      
    console.log(str.search(/is/) )   
    //8

 search() will determine case

    var str='my name is gf '  
      
    console.log(str.search(/Is/) )  
    //-1

 

    var str='my name is gf '  
      
    console.log(str.search(/Is/i) )  
    // Add i to ignore case
    //8

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326768030&siteId=291194637