Replace multiple strings with multiple other strings

前端 未结 18 1996
别那么骄傲
别那么骄傲 2020-11-22 04:14

I\'m trying to replace multiple words in a string with multiple other words. The string is \"I have a cat, a dog, and a goat.\"

However, this does not produce \"I ha

相关标签:
18条回答
  • 2020-11-22 04:47

    using Array.prototype.reduce():

    const arrayOfObjects = [
      { plants: 'men' },
      { smart:'dumb' },
      { peace: 'war' }
    ]
    const sentence = 'plants are smart'
    
    arrayOfObjects.reduce(
      (f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence
    )
    
    // as a reusable function
    const replaceManyStr = (obj, sentence) => obj.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)
    
    const result = replaceManyStr(arrayOfObjects , sentence1)
    

    Example

    // /////////////    1. replacing using reduce and objects
    
    // arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)
    
    // replaces the key in object with its value if found in the sentence
    // doesn't break if words aren't found
    
    // Example
    
    const arrayOfObjects = [
      { plants: 'men' },
      { smart:'dumb' },
      { peace: 'war' }
    ]
    const sentence1 = 'plants are smart'
    const result1 = arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence1)
    
    console.log(result1)
    
    // result1: 
    // men are dumb
    
    
    // Extra: string insertion python style with an array of words and indexes
    
    // usage
    
    // arrayOfWords.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence)
    
    // where arrayOfWords has words you want to insert in sentence
    
    // Example
    
    // replaces as many words in the sentence as are defined in the arrayOfWords
    // use python type {0}, {1} etc notation
    
    // five to replace
    const sentence2 = '{0} is {1} and {2} are {3} every {5}'
    
    // but four in array? doesn't break
    const words2 = ['man','dumb','plants','smart']
    
    // what happens ?
    const result2 = words2.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence2)
    
    console.log(result2)
    
    // result2: 
    // man is dumb and plants are smart every {5}
    
    // replaces as many words as are defined in the array
    // three to replace
    const sentence3 = '{0} is {1} and {2}'
    
    // but five in array
    const words3 = ['man','dumb','plant','smart']
    
    // what happens ? doesn't break
    const result3 = words3.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence3)
    
    console.log(result3)
    
    // result3: 
    // man is dumb and plants

    0 讨论(0)
  • 2020-11-22 04:47
    String.prototype.replaceSome = function() {
        var replaceWith = Array.prototype.pop.apply(arguments),
            i = 0,
            r = this,
            l = arguments.length;
        for (;i<l;i++) {
            r = r.replace(arguments[i],replaceWith);
        }
        return r;
    }
    

    /* replaceSome method for strings it takes as ,much arguments as we want and replaces all of them with the last argument we specified 2013 CopyRights saved for: Max Ahmed this is an example:

    var string = "[hello i want to 'replace x' with eat]";
    var replaced = string.replaceSome("]","[","'replace x' with","");
    document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)
    

    */

    jsFiddle: http://jsfiddle.net/CPj89/

    0 讨论(0)
  • 2020-11-22 04:49

    All solutions work great, except when applied in programming languages that closures (e.g. Coda, Excel, Spreadsheet's REGEXREPLACE).

    Two original solutions of mine below use only 1 concatenation and 1 regex.

    Method #1: Lookup for replacement values

    The idea is to append replacement values if they are not already in the string. Then, using a single regex, we perform all needed replacements:

    var str = "I have a cat, a dog, and a goat.";
    str = (str+"||||cat,dog,goat").replace(
       /cat(?=[\s\S]*(dog))|dog(?=[\s\S]*(goat))|goat(?=[\s\S]*(cat))|\|\|\|\|.*$/gi, "$1$2$3");
    document.body.innerHTML = str;

    Explanations:

    • cat(?=[\s\S]*(dog)) means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise.
    • Same for "dog" that would capture "goat" as group 2, and "goat" that would capture "cat" as group 3.
    • We replace with "$1$2$3" (the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above cases
    • If we manually appended replacements to the string like str+"||||cat,dog,goat", we remove them by also matching \|\|\|\|.*$, in which case the replacement "$1$2$3" will evaluate to "", the empty string.

    Method #2: Lookup for replacement pairs

    One problem with Method #1 is that it cannot exceed 9 replacements at a time, which is the maximum number of back-propagation groups. Method #2 states not to append just replacement values, but replacements directly:

    var str = "I have a cat, a dog, and a goat.";
    str = (str+"||||,cat=>dog,dog=>goat,goat=>cat").replace(
       /(\b\w+\b)(?=[\s\S]*,\1=>([^,]*))|\|\|\|\|.*$/gi, "$2");
    document.body.innerHTML = str;

    Explanations:

    • (str+"||||,cat=>dog,dog=>goat,goat=>cat") is how we append a replacement map to the end of the string.
    • (\b\w+\b) states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else.
    • (?=[\s\S]*...) is a forward lookup that will typically go to the end of the document until after the replacement map.
      • ,\1=> means "you should find the matched word between a comma and a right arrow"
      • ([^,]*) means "match anything after this arrow until the next comma or the end of the doc"
    • |\|\|\|\|.*$ is how we remove the replacement map.
    0 讨论(0)
  • 2020-11-22 04:53
        var str = "I have a cat, a dog, and a goat.";
    
        str = str.replace(/goat/i, "cat");
        // now str = "I have a cat, a dog, and a cat."
    
        str = str.replace(/dog/i, "goat");
        // now str = "I have a cat, a goat, and a cat."
    
        str = str.replace(/cat/i, "dog");
        // now str = "I have a dog, a goat, and a cat."
    
    0 讨论(0)
  • 2020-11-22 04:55

    You can find and replace string using delimiters.

    var obj = {
      'firstname': 'John',
      'lastname': 'Doe'
    }
    
    var text = "My firstname is {firstname} and my lastname is {lastname}"
    
    alert(mutliStringReplace(obj,text))
    
    function mutliStringReplace(object, string) {
          var val = string
          var entries = Object.entries(object);
          entries.forEach((para)=> {
              var find = '{' + para[0] + '}'
              var regExp = new RegExp(find,'g')
           val = val.replace(regExp, para[1])
        })
      return val;
    }

    0 讨论(0)
  • 2020-11-22 04:58

    Solution with Jquery (first include this file): Replace multiple strings with multiple other strings:

    var replacetext = {
        "abc": "123",
        "def": "456"
        "ghi": "789"
    };
    
    $.each(replacetext, function(txtorig, txtnew) {
        $(".eng-to-urd").each(function() {
            $(this).text($(this).text().replace(txtorig, txtnew));
        });
    });
    
    0 讨论(0)
提交回复
热议问题