代码之家  ›  专栏  ›  技术社区  ›  Omar Abid

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

  •  391
  • Omar Abid  · 技术社区  · 16 年前

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

    例如,我有:

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

    我想得到: okay this is a string .

    到目前为止,我试着:

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

    但最终所有字符串都被替换为空格。

    14 回复  |  直到 8 年前
        1
  •  704
  •   Wiktor Stribiżew    8 年前

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

    mystring = mystring.replace(/\./g,' ')
    
        2
  •  297
  •   insertusernamehere    13 年前

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

    var newstring = mystring.split('.').join(' ');
    
        3
  •  52
  •   Fagner Brack    10 年前
    /**
     * 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('.', ' '));
    

    比使用regex更快…

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

    编辑2:
    我已经创建了一个lib,允许您使用一个流畅的界面来完成这项工作:

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

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

        4
  •  22
  •   macemers    14 年前
    str.replace(new RegExp(".","gm")," ")
    
        5
  •  13
  •   Victor pozs    12 年前

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

    你可以试试这个:

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

    问候语

        6
  •  6
  •   kittichart    13 年前

    我在这个点上加了双反斜杠使它起作用。欢呼。

    var st = "okay.this.is.a.string";
    var Re = new RegExp("\\.","g");
    st = st.replace(Re," ");
    alert(st);
    
        7
  •  4
  •   sstur    13 年前

    这比fagner brack(tolowercase not performed in loop)发布的更简洁/可读,性能应该更好:

    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);
    }
    

    用途:

    alert('Bananas And Bran'.replaceAll('An', '(an)'));
    
        8
  •  2
  •   Joel    13 年前
    String.prototype.replaceAll = function(character,replaceChar){
        var word = this.valueOf();
    
        while(word.indexOf(character) != -1)
            word = word.replace(character,replaceChar);
    
        return word;
    }
    
        9
  •  2
  •   scripto    13 年前

    这是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;
        };
    

    然后您可以使用它:

    var mytext=“我叫乔治”;
    var newtext=mytext.replaceall(“乔治”,“迈克尔”);

        10
  •  0
  •   Brandon Anzaldi    11 年前

    示例:我想将所有双引号(“)替换为单引号('),然后代码将如下所示

    var str= "\"Hello\""
    var regex = new RegExp('"', 'g');
    str = str.replace(regex, '\'');
    console.log(str); // 'Hello'
    
        11
  •  0
  •   A T    10 年前

    @脚本变得更加简洁 prototype :

    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;
    }
    

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

        12
  •  0
  •   Danon TylerDurden    9 年前
    String.prototype.replaceAll = function (needle, replacement) {
        return this.replace(new RegExp(needle, 'g'), replacement);
    };
    
        13
  •  -1
  •   tomvodi    11 年前

    可以使用regexp javasscript对象替换任何字符串/字符的所有匹配项。

    这是密码,

    var mystring = 'okay.this.is.a.string';
    
    var patt = new RegExp("\\.");
    
    while(patt.test(mystring)){
    
      mystring  = mystring .replace(".","");
    
    }
    
        14
  •  -5
  •   Neha    13 年前
    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, "'");
    }