Replace multiple strings with multiple other strings

前端 未结 18 1998
别那么骄傲
别那么骄傲 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 05:07

    I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

    var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
    

    which will replace the {0} and {1} with the array items and return the following string

    "this is a test string for stringInject"
    

    or you could replace placeholders with object keys and values like so:

    var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
    
    "My username is tjcafferkey on Github" 
    
    0 讨论(0)
  • user regular function to define the pattern to replace and then use replace function to work on input string,

    var i = new RegExp('"{','g'),
        j = new RegExp('}"','g'),
        k = data.replace(i,'{').replace(j,'}');
    
    0 讨论(0)
  • 2020-11-22 05:09

    by using prototype function we can replace easily by passing object with keys and values and replacable text

    String.prototype.replaceAll=function(obj,keydata='key'){
     const keys=keydata.split('key');
     return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
    }
    
    const data='hids dv sdc sd ${yathin} ${ok}'
    console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))

    0 讨论(0)
  • 2020-11-22 05:11

    Just in case someone is wondering why the original poster's solution is not working:

    var str = "I have a cat, a dog, and a goat.";
    
    str = str.replace(/cat/gi, "dog");
    // now str = "I have a dog, a dog, and a goat."
    
    str = str.replace(/dog/gi, "goat");
    // now str = "I have a goat, a goat, and a goat."
    
    str = str.replace(/goat/gi, "cat");
    // now str = "I have a cat, a cat, and a cat."
    
    0 讨论(0)
  • 2020-11-22 05:12

    This may not meet your exact need in this instance, but I've found this a useful way to replace multiple parameters in strings, as a general solution. It will replace all instances of the parameters, no matter how many times they are referenced:

    String.prototype.fmt = function (hash) {
            var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
    }
    

    You would invoke it as follows:

    var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
    // person = 'Agent Jack Bauer'
    
    0 讨论(0)
  • 2020-11-22 05:13

    You can use https://www.npmjs.com/package/union-replacer for this purpose. It is basically a string.replace(regexp, ...) counterpart, which allows multiple replaces to happen in one pass while preserving full power of string.replace(...).

    Disclosure: I am the author. The library was developed to support more complex user-configurable replacements and it addresses all the problematic things like capture groups, backreferences and callback function replacements.

    The solutions above are good enough for exact string replacements though.

    0 讨论(0)
提交回复
热议问题