How to replace all dots in a string using JavaScript
I want to replace all the occurrences of a dot( .
) in a JavaScript string
For example, I have:
var mystring = 'okay.this.is.a.string';
I want to get: okay this is a string
.
So far I tried:
mystring.replace(/./g,' ')
but this ends up with all the string replaced to spaces.
You need to escape the .
because it has the meaning of "an arbitrary character" in a regular expression.
mystring = mystring.replace(/./g,' ')
一个更容易理解的解决方案:)
var newstring = mystring.split('.').join(' ');
/**
* ReplaceAll by Fagner Brack (MIT Licensed)
* Replaces all occurrences of a substring in a string
*/
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
_token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
alert('okay.this.is.a.string'.replaceAll('.', ' '));
Faster than using regex...
EDIT:
Maybe at the time I did this code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid, even if the performance differs from the regex approach.
EDIT2:
I have created a lib that allows you to do this using a fluent interface:
replace('.').from('okay.this.is.a.string').with(' ');
See https://github.com/FagnerMartinsBrack/str-replace.
链接地址: http://www.djcxy.com/p/94178.html上一篇: 使用Spark的值数据库