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"
Author by
Gustavo Porto
Updated on July 07, 2020Comments
-
Gustavo Porto almost 4 years
I'm trying to replace the value of
item
with values in the arrayarr
, but I only get that if I use:arr [1]
,arr [2]
... if I just letarr
, returnsabcdefg
.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 almost 13 yearsWhat 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 almost 13 yearsyou may need to do foreach item in array, do replacement.
-
Gustavo Porto almost 13 yearscan you help me with this? :(
-
agent-j almost 13 years@GtOkAi, I added some code. Is that what you're looking for?
-
Gustavo Porto almost 13 yearsYes! Exactly! It would only be to the contrary, changing the admin change by 1 and 2 per guest
-
agent-j almost 13 years@GtOkAi, I changed the sample.
-
Gustavo Porto almost 13 yearsYeah! I had managed to make the change, thank you! I feel obligated now studying JS. Thanks again, helped a lot!
-
wizzwizz4 almost 8 yearsIt 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 almost 5 years
split
was deprecated in PHP 5.3 and removed in PHP 7.0. Perhaps time for an update?