When i try to put an array into a JavaScript array, a la,
> `${[1,2,3]}`
I get back this
'1,2,3'
and not
'[1,2,3]'
in the latest Node & Chrome.
I am missing something incredibly obvious, but need it spelled out to me nevertheless : )
You should use JSON.stringify(array)
It can help you to predict conversion to the string any arrays in this array.
const array = [["expected","test",1],0];
const arrayStr = JSON.stringify(array);
const templateResAsString = `${array}`; // expected,test,1,0
const templateResAsarray = `${arrayStr}`; // [["expected","test",1],0]
By the default, the values that are interpolated into a template literal are converted to their string representation.
For objects that means calling their .toString() method. The string representation of an array is simply a comma separated list of the strings representation of its elements, without leading [ or trailing ]:
console.log(
[1,2,3].toString()
);
Consolodiated list including above answers:
const arr = [1,2,3,4,5,'foo','bar','baz']
console.log(JSON.stringify(arr));
console.log(JSON.stringify(arr, null, 2));
console.log(arr.toString());
console.log(`${arr}`);
console.log(arr.join('\n'));
Good Luck...
Related
Is it somehow possible to convert a string to an array as easy as possible without any hacks? and without splitting the string at some point?
For example bringing this:
temp = 'Text';
to this:
temp = ['Text'];
It might be a simple question but I couldn't find any solution without splitting the string.
const temp = 'text';
console.log(new Array(temp));
console.log([temp]);
console.log(temp.split());
console.log([].concat(temp));
There are a few options out there.
If you want an array with the string as a single value just create a new array with that string.
temp = [temp];
How can I take something in the form of
[["[]",2,"c"],["d","e","f"]]
and log
[["[]","2","c"],["d","e","f"]]
to the console?
I have tried console.log(array.toString()) but that just logs
[[[],2,c],[d,e,f]]
You can use JSON.stringify and log that
console.log(JSON.stringify([["[]",2,"c"],["d","e","f"]]))
If u want to preserve double quotes " then you can use
console.log(${'[["[]",2,"c"],["d","e","f"]]'})
else u can use
console.log(JSON.stringify([["[]",2,"c"],["d","e","f"]]))
This will preserve the arrays and only turn the the inner array items into strings.
var data = [["[]",2,"c"],["d","e","f"]];
var stringed = data.map((d)=>{
return (d.toString().split(","))
});
console.log(stringed);
I need to parse a complex URL string to fetch specific values.
From the following URL string:
/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss
I need to extract this result in array format:
['http://any-feed-url-a.com?filter=hot&format=rss', 'http://any-feed-url-b.com?filter=rising&format=rss']
I tried already with this one /url=([^&]+)/ but I can't capture all correctly all the query parameters. And I would like to omit the url=.
RegExr link
Thanks in advance.
This regex works for me: url=([a-z:/.?=-]+&[a-z=]+)
also, you can test this: /http(s)?://([a-z-.?=&])+&/g
const string = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&url=http://any-feed-url.com?filter=latest&format=rss'
const string2 = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&next=parm&url=http://any-feed-url.com?filter=latest&format=rss'
const regex = /url=([a-z:/.?=-]+&[a-z=]+)/g;
const regex2 = /http(s)?:\/\/([a-z-.?=&])+&/g;
console.log(string.match(regex))
console.log(string2.match(regex2))
have you tried to use split method ? instead of using regex.
const urlsArr = "/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss".split("url=");
urlsArr.shift(); // removing first item from array -> "/api/rss/feeds?"
console.log(urlsArr)
)
which is going to return ["/api/rss/feeds?", "http://any-feed-url-a.com?filter=hot&format=rss&", "http://any-feed-url-b.com?filter=rising&format=rss"] then i am dropping first item in array
if possible its better to use something else then regex CoddingHorror: regular-expressions-now-you-have-two-problems
You can matchAll the url's, then map the capture group 1 to an array.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
arr = [...str.matchAll(/url=(.*?)(?=&url=|$)/g)].map(x => x[1])
console.log(arr)
But matchAll isn't supported by older browsers.
But looping an exec to fill an array works also.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
re = /url=(.*?)(?=&url=|$)/g;
arr = [];
while (m = re.exec(str)) {
arr.push(m[1]);
}
console.log(arr)
If your input is better-formed in reality than shown in the question and you’re targeting a modern JavaScript environment, there’s URL/URLSearchParams:
const input = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot%26format=rss&url=http://any-feed-url-b.com?filter=rising%26format=rss';
const url = new URL(input, 'http://example.com/');
console.log(url.searchParams.getAll('url'));
Notice how & has to be escaped as %26 for it to make sense.
Without this input in a standard form, it’s not clear which rules of URLs are still on the table.
I've a string
var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";
I need to convert it into an array of list. For example,
alert(my_str[1])
would give an output of 1,15.
I've tried the following:
var myarray = JSON.parse(my_str);
but it throws the error "unexpected token ( in JSON at position 1"
I tried this
var myarray = JSON.parse(my_str);
but it throws error "unexpected token ( in JSON at position 1"
So I changed the structure of my string to:
var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";
That worked like a charm ;)
The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")".
Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.
var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))
you can now work on my_array object and retrieve couples of numbers using array indexes
my_array[1] ---> 1,15
You have to replace ( by '( and ) by )' ,, then , apply eval :
eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]
This is a pretty naive idea, but does work (without JSON.parse or eval):
var arr = my_str.replace('[(', '').replace(')]', '').split('),(');
//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]
var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)
This is probably very elementary, but I'm still learning.
I've imported a record from an XML file and have the result :
"a,b,c,d,e,f,g,h"
I would like to end up with 8 separate variables, one for each comma delimited value.
What is the shortest way to code this using javascript?
if you .split() the list, you'll end up with a single array with 'n' number of elements. Not -exactly- 8 separate variables, but 8 elements that can be accessed individually.
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split( ',' );
alert( myArray[ 4 ] );
use split()
js>s = "a,b,c,d,e,f,g,h"
a,b,c,d,e,f,g,h
js>a = s.split(',')
a,b,c,d,e,f,g,h
js>a[0]
a
js>a[4]
e
Use split().
In your case, xml_string.split(',');
If you have the result as a string, use the split method on it:
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split(",");