Home > Mobile >  How to convert request query id = '[12eetftt76237,jhgasduyas7657]' to array of elements or
How to convert request query id = '[12eetftt76237,jhgasduyas7657]' to array of elements or

Time:03-03

so this is a hapijs, typescript project. I need to send an array of id s as params through request URL.

URL example : localhost:3444/?id='[askjajk78686,ajshd67868]'

I tried split(',') but, the result i get is

'[qweqwe121212312,iojqwio78788768]'.split(',');

result = ['[qweqwe121212312', 'iojqwio78788768]']

the result have '[' (in it look above result), i need id(qweqwe121212312) with out '['

I need to map through eact element to do some tasks, so i need result as ['asdad32323','zxccscssd33'];

Any ideas ?

CodePudding user response:

If the array elements don't include [ or ] then you could just replace them and them with empty strings and then split it

id.replaceAll(']','').replaceAll('[','').split(',')

But, most likely you need to rethink how you are sending the params. You should encode it as a JSON, so you could simply use JSON.parse(id)

CodePudding user response:

Get rid of brackets with slice, then you can split it as you want.

let str = '[qweqwe121212312,iojqwio78788768]'
const res = str.slice(1,-1).split(',')

CodePudding user response:

To get elements from your string, you can use regex.

\w matches any word character (equivalent to [a-zA-Z0-9_])

const valuesString = '[qweqwe121212312,iojqwio78788768]';

const values = valuesString.match(/\w /g); // get values via regex;

console.log(values[0], values[1])

  • Related