js implements string replaceAll method

demand

Want to replace all a character or string in a string For
example:'asdas;;;asfaf;;'Replace the';'

achieve

In other languages, there is a replaceAll method, but js does not provide this method. So you can use regular expressions for query substitution.

'asdas;;;asfaf;;'.replace(/;/g,'')

g: Global matching
Operation result: It is
Insert picture description here
more straightforward to create a new regular expression object and set it

'asdas;;;asfaf;;'.replace(new RegExp(";","gm"),'')

operation result:
Insert picture description here

General method

function replaceAll(str)  
{
    
      
    if(str!=null)
    	str = str.replace(/;/g, '');
    return str;  
}  

Binding the prototype method on the String object

String.prototype.replaceAll  = function(before,after){
    
         
    return this.replace(new RegExp(before,"gm"),after);     
}

Guess you like

Origin blog.csdn.net/KaiSarH/article/details/108847126