Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to replace [ ] and "?

I am sending a Array from PHP encoded it to JSON and send it to a JavaScript value. Now I wanted to split the Array on comma's ,. This worked fine, but when calling the very first and last string inside the array I can see a [, ] and ".

I can get the " gone, but the [ and ] seems to be a problem.

my code now:

data_array[i].replace(/["[]]/g,"");
like image 444
user1614456 Avatar asked Jun 26 '26 08:06

user1614456


2 Answers

If you transfer a string value like "[5,4,7,2,1]" from PHP to Javascript, you should rather JSON decode it into a native Javascript object/array.

var receivedData = "[5,4,7,2,1]";
    receivedData = JSON.parse( receivedData );

From that point on, you may just access receivedData like a normal Array

console.log( receivedData[ 2 ] );  // 7
like image 132
jAndy Avatar answered Jun 28 '26 22:06

jAndy


You should escape the special chars:

data_array[i].replace(/["[\]]/g,"");
like image 28
gion_13 Avatar answered Jun 28 '26 21:06

gion_13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!