我想替换.JavaScript 字符串中所有出现的点()
例如,我有:
var mystring = 'okay.this.is.a.string';
我想得到:okay this is a string。
到目前为止,我尝试过:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
我想替换.JavaScript 字符串中所有出现的点()
例如,我有:
var mystring = 'okay.this.is.a.string';
我想得到:okay this is a string。
到目前为止,我尝试过:
mystring.replace(/./g,' ')
但这最终将所有字符串替换为空格。
您需要转义 the.因为它在正则表达式中具有“任意字符”的含义。
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('.', ' '));
比使用正则表达式更快...
编辑:
也许在我做这段代码的时候我没有使用 jsperf。但最终这样的讨论完全没有意义,性能差异不值得现实世界中代码的易读性,所以我的回答仍然有效,即使性能与正则表达式方法不同。
EDIT2:
我创建了一个库,允许您使用流畅的界面执行此操作:
replace('.').from('okay.this.is.a.string').with(' ');
str.replace(new RegExp(".","gm")," ")
对于这个简单的场景,我还建议使用 javascript 中内置的方法。
你可以试试这个:
"okay.this.is.a.string".split(".").join("")
问候