Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using split/join to replace a string with an array

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"));
like image 772
Gustavo Porto Avatar asked Jun 22 '11 15:06

Gustavo Porto


People also ask

Does split turn a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split an element in a string array?

You can simply use the String#split method on any element of the array, whose delimiter can be any character.

How do you replace a part of a string with something else?

If you'd like to replace a substring with another string, simply use the REPLACE function. This function takes three arguments: The string to change (which in our case was a column). The substring to replace.

What is split () function in string?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


2 Answers

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.
like image 131
agent-j Avatar answered Sep 22 '22 18:09

agent-j


Split uses regular expressions, so

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

If you are trying to replace a string:

"abcdef".replace('abc','zzz') == "zzzdef"
like image 29
Justin Thomas Avatar answered Sep 23 '22 18:09

Justin Thomas