Using split/join to replace a string with an array

31,300

Solution 1

Use:

var item = 'Hello, 1, my name is 2.';
var arr = new Array();
arr [1] = 'admin';
arr [2] = 'guest';
for (var x in arr)
    item = item.replace(x, arr[x]);
alert(item);

It produces:

Hello, admin, my name is guest.

Solution 2

Split uses regular expressions, so

"My String".split('S') == ["My ","tring"]

If you are trying to replace a string:

"abcdef".replace('abc','zzz') == "zzzdef"
Share:
31,300
Gustavo Porto
Author by

Gustavo Porto

Updated on July 07, 2020

Comments

  • Gustavo Porto
    Gustavo Porto almost 4 years

    I'm trying to replace the value of item with values ​​in the array arr, but I only get that if I use: arr [1], arr [2] ... if I just let arr, returns abcdefg.

    I am PHP programmer, and I have a minimal notion with JavaScript, can someone give me a light?

    var item = 'abcdefg';
    var arr = new Array();
    arr[1] = "zzz";
    arr[2] = "abc";
    var test = item.split(arr);
    alert(test.join("\n"));
    
  • Gustavo Porto
    Gustavo Porto almost 13 years
    What I'm trying to do is replace the IDs with names, example: id 1 - admin id 2 - guest id 3 - test1 id 4 - test2 These values​​, I would have in an array (arr [1] = admin, arr [2] = guest, etc.), the string value item, would be the id, so I searched the id in the array array and replace the name .
  • agent-j
    agent-j almost 13 years
    you may need to do foreach item in array, do replacement.
  • Gustavo Porto
    Gustavo Porto almost 13 years
    can you help me with this? :(
  • agent-j
    agent-j almost 13 years
    @GtOkAi, I added some code. Is that what you're looking for?
  • Gustavo Porto
    Gustavo Porto almost 13 years
    Yes! Exactly! It would only be to the contrary, changing the admin change by 1 and 2 per guest
  • agent-j
    agent-j almost 13 years
    @GtOkAi, I changed the sample.
  • Gustavo Porto
    Gustavo Porto almost 13 years
    Yeah! I had managed to make the change, thank you! I feel obligated now studying JS. Thanks again, helped a lot!
  • wizzwizz4
    wizzwizz4 almost 8 years
    It uses regular expressions, i.e. /[a-z]+/ or strings, i.e. "/[a-z]+/". The former splits on any block of lower-case letters, the latter on the literal string /[a-z]+/.
  • Peter Mortensen
    Peter Mortensen almost 5 years