简体   繁体   中英

Remove multiple square brackets using replace() - javascript

I have a response from the server that is like this:

users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]

It's a string not an array like it appear, since I need an array to work on, how I can remove the square backets and then the commas to obtain a normal array? I've tried in this way:

var data = ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
data.replace('[', '').replace(']', '').split(',');

but chaining two .replace() functions and a split() isn't the best solution. Can anyone halp me?

In your example data is an array.

However, if data was a string you would convert it to an array like this:

var arr = JSON.parse(data);

In short, Here you have provided data in normal string formate not in JSON string formate

 var data = 'users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]' var squareBracketData = data.substr(data.indexOf("[")) var array = JSON.parse(squareBracketData) console.log(array)

Some personal advice, Try to send JSON stringify data from the server so it will make your life easy

Example:

 var users =["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"] // Stringify data var data = JSON.stringify({users}) console.log("Data") console.log(data) // retrieve data from string var parsedData = JSON.parse(data) var parsedUsers = parsedData.users console.log("parsedUsers") console.log(parsedUsers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM