如何使用JavaScript替换字符串中的所有点

时间:2021-09-22 09:31:13

I want to replace all the occurrences of a dot(.) in a JavaScript string

我想替换JavaScript字符串中出现的所有点(.)

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.

但是最后所有的字符串都换成了空格。

14 个解决方案

#1


656  

You need to escape the . because it has the meaning of "an arbitrary character" in a regular expression.

你需要逃离。因为它在正则表达式中具有“任意字符”的含义。

mystring = mystring.replace(/\./g,' ')

#2


294  

One more solution which is easy to understand :)

还有一个很容易理解的解决方案:

var newstring = mystring.split('.').join(' ');

#3


53  

/**
 * 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.

编辑:也许在我做这段代码的时候,我没有使用jsperf。但是最后这种讨论是完全没有意义的,性能差异不值得代码在现实世界中的易读性,所以我的答案仍然有效,即使性能与regex方法不同。

EDIT2:
I have created a lib that allows you to do this using a fluent interface:

EDIT2:我创建了一个lib,允许您使用一个流畅的接口来完成这个任务:

replace('.').from('okay.this.is.a.string').with(' ');

See https://github.com/FagnerMartinsBrack/str-replace.

见https://github.com/FagnerMartinsBrack/str-replace。

#4


22  

str.replace(new RegExp(".","gm")," ")

#5


13  

For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.

对于这个简单的场景,我还建议使用javascript中内置的方法。

You could try this :

你可以试试这个:

"okay.this.is.a.string".split(".").join("")

Greetings

问候

#6


6  

I add double backslash to the dot to make it work. Cheer.

我在点上添加双反斜杠以使它工作。欢呼。

var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);

#7


4  

This is more concise/readable and should perform better than the one posted by Fagner Brack (toLowerCase not performed in loop):

这比Fagner Brack(未在循环中执行的toLowerCase)更简洁/可读,并且应该执行得更好。

String.prototype.replaceAll = function(search, replace, ignoreCase) {
  if (ignoreCase) {
    var result = [];
    var _string = this.toLowerCase();
    var _search = search.toLowerCase();
    var start = 0, match, length = _search.length;
    while ((match = _string.indexOf(_search, start)) >= 0) {
      result.push(this.slice(start, match));
      start = match + length;
    }
    result.push(this.slice(start));
  } else {
    result = this.split(search);
  }
  return result.join(replace);
}

Usage:

用法:

alert('Bananas And Bran'.replaceAll('An', '(an)'));

#8


2  

String.prototype.replaceAll = function(character,replaceChar){
    var word = this.valueOf();

    while(word.indexOf(character) != -1)
        word = word.replace(character,replaceChar);

    return word;
}

#9


2  

Here's another implementation of replaceAll. Hope it helps someone.

这是replaceAll的另一个实现。希望它能帮助一些人。

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

Then you can use it:

然后你可以使用它:

var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

var myText = "My Name is George";var newText = myText。replaceAll(“乔治”,“迈克尔”);

#10


0  

Example: I want to replace all double Quote (") into single Quote (') Then the code will be like this

示例:我想将所有双引号(")替换为单引号('),那么代码将是这样的

var str= "\"Hello\""
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
console.log(str); // 'Hello'

#11


0  

@scripto's made a bit more concise and without prototype:

@scripto更简洁,没有原型:

function strReplaceAll(s, stringToFind, stringToReplace) {
    if (stringToFind === stringToReplace) return s;
    for (let index = s.indexOf(stringToFind); index != -1; index = s.indexOf(stringToFind))
        s = s.replace(stringToFind, stringToReplace);
    return s;
}

Here's how it stacks up: http://jsperf.com/replace-vs-split-join-vs-replaceall/68

下面是它的堆叠方式:http://jsperf.com/replace-vs- spli- join-vs-replaceall/68

#12


0  

String.prototype.replaceAll = function (needle, replacement) {
    return this.replace(new RegExp(needle, 'g'), replacement);
};

#13


-1  

you can replace all occurrence of any string/character using RegExp javasscript object.

您可以使用RegExp javasscript对象替换所有出现的字符串/字符。

Here is the code,

这是代码,

var mystring = 'okay.this.is.a.string';

var patt = new RegExp("\\.");

while(patt.test(mystring)){

  mystring  = mystring .replace(".","");

}

#14


-5  

var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);

function escapeHtml(text) {
if('' !== text) {
    return text.replace(/&/g, "&")
               .replace(/&lt;/g, "<")
               .replace(/&gt;/g, ">")
               .replace(/\./g,' ')
               .replace(/&quot;/g, '"')
               .replace(/&#39/g, "'");
} 

#1


656  

You need to escape the . because it has the meaning of "an arbitrary character" in a regular expression.

你需要逃离。因为它在正则表达式中具有“任意字符”的含义。

mystring = mystring.replace(/\./g,' ')

#2


294  

One more solution which is easy to understand :)

还有一个很容易理解的解决方案:

var newstring = mystring.split('.').join(' ');

#3


53  

/**
 * 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.

编辑:也许在我做这段代码的时候,我没有使用jsperf。但是最后这种讨论是完全没有意义的,性能差异不值得代码在现实世界中的易读性,所以我的答案仍然有效,即使性能与regex方法不同。

EDIT2:
I have created a lib that allows you to do this using a fluent interface:

EDIT2:我创建了一个lib,允许您使用一个流畅的接口来完成这个任务:

replace('.').from('okay.this.is.a.string').with(' ');

See https://github.com/FagnerMartinsBrack/str-replace.

见https://github.com/FagnerMartinsBrack/str-replace。

#4


22  

str.replace(new RegExp(".","gm")," ")

#5


13  

For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.

对于这个简单的场景,我还建议使用javascript中内置的方法。

You could try this :

你可以试试这个:

"okay.this.is.a.string".split(".").join("")

Greetings

问候

#6


6  

I add double backslash to the dot to make it work. Cheer.

我在点上添加双反斜杠以使它工作。欢呼。

var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);

#7


4  

This is more concise/readable and should perform better than the one posted by Fagner Brack (toLowerCase not performed in loop):

这比Fagner Brack(未在循环中执行的toLowerCase)更简洁/可读,并且应该执行得更好。

String.prototype.replaceAll = function(search, replace, ignoreCase) {
  if (ignoreCase) {
    var result = [];
    var _string = this.toLowerCase();
    var _search = search.toLowerCase();
    var start = 0, match, length = _search.length;
    while ((match = _string.indexOf(_search, start)) >= 0) {
      result.push(this.slice(start, match));
      start = match + length;
    }
    result.push(this.slice(start));
  } else {
    result = this.split(search);
  }
  return result.join(replace);
}

Usage:

用法:

alert('Bananas And Bran'.replaceAll('An', '(an)'));

#8


2  

String.prototype.replaceAll = function(character,replaceChar){
    var word = this.valueOf();

    while(word.indexOf(character) != -1)
        word = word.replace(character,replaceChar);

    return word;
}

#9


2  

Here's another implementation of replaceAll. Hope it helps someone.

这是replaceAll的另一个实现。希望它能帮助一些人。

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

Then you can use it:

然后你可以使用它:

var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

var myText = "My Name is George";var newText = myText。replaceAll(“乔治”,“迈克尔”);

#10


0  

Example: I want to replace all double Quote (") into single Quote (') Then the code will be like this

示例:我想将所有双引号(")替换为单引号('),那么代码将是这样的

var str= "\"Hello\""
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
console.log(str); // 'Hello'

#11


0  

@scripto's made a bit more concise and without prototype:

@scripto更简洁,没有原型:

function strReplaceAll(s, stringToFind, stringToReplace) {
    if (stringToFind === stringToReplace) return s;
    for (let index = s.indexOf(stringToFind); index != -1; index = s.indexOf(stringToFind))
        s = s.replace(stringToFind, stringToReplace);
    return s;
}

Here's how it stacks up: http://jsperf.com/replace-vs-split-join-vs-replaceall/68

下面是它的堆叠方式:http://jsperf.com/replace-vs- spli- join-vs-replaceall/68

#12


0  

String.prototype.replaceAll = function (needle, replacement) {
    return this.replace(new RegExp(needle, 'g'), replacement);
};

#13


-1  

you can replace all occurrence of any string/character using RegExp javasscript object.

您可以使用RegExp javasscript对象替换所有出现的字符串/字符。

Here is the code,

这是代码,

var mystring = 'okay.this.is.a.string';

var patt = new RegExp("\\.");

while(patt.test(mystring)){

  mystring  = mystring .replace(".","");

}

#14


-5  

var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);

function escapeHtml(text) {
if('' !== text) {
    return text.replace(/&amp;/g, "&")
               .replace(/&lt;/g, "<")
               .replace(/&gt;/g, ">")
               .replace(/\./g,' ')
               .replace(/&quot;/g, '"')
               .replace(/&#39/g, "'");
}