How to replace multiple strings with the .replace() Method?

前端 未结 3 1178
情歌与酒
情歌与酒 2020-12-05 19:02

I want to make a content editable div in which I replace explicit words with asterisks. This is my JavaScript code:

function censorText(){
    var explicit          


        
3条回答
  •  清歌不尽
    2020-12-05 19:30

    A generic way to handle this is as follows:

    Establish a dictionary and build a regexp:

      var dictionary = { bad: 'good', worse: 'better', awful: 'wonderful'},
          regexp = RegExp ('\\b(' + Object.keys (dictionary).join ('|') + ')\\b', 'g');
    

    The regexp is constructed from the dictionary key words (note they must not contain RegExp special characters).

    Now do a replace, using a function in the place of the replacing string, the function simply return the value of the corresponding key.

      text = text.replace (regexp, function (_, word) { return dictionary[word]; });
    

    The OP made no reference to upper/lower case. The following caters for initial and all caps and wraps the code as a function :

      function clean (text) {
        var dictionary = { bad: 'good', worse: 'better', awful: 'wonderful'},
            regexp = RegExp ('\\b(' + Object.keys (dictionary).join ('|') + ')\\b', 'ig');
    
        return text.replace (regexp, function (_, word) { 
          _ = dictionary[word.toLowerCase ()];
          if (/^[A-Z][a-z]/.test (word)) // initial caps
            _ = _.slice (0,1).toUpperCase () + _.slice (1);
          else if (/^[A-Z][A-Z]/.test (word)) // all caps
            _ = _.toUpperCase ();
          return _;
        });
      }
    

    See the fiddle : http://jsfiddle.net/nJNq2/

提交回复
热议问题