Why cant i convert this arr
let stringarr = "[2022/07/12, 2022/08/09]"
to this arr
let arr = JSON.parse(stringarr) ---> error
Unexpected token / in JSON at position 5
It's not valid JSON, since the array elements aren't quoted.
If the array elements are all dates formatted like that, you could use a regular expression to extract them.
let stringarr = "[2022/07/12, 2022/08/09]"
let dates = stringarr.match(/\d{4}\/\d{2}\/\d{2}/g);
console.log(dates);
what can i do then to convert it to an array
There are several ways to do that, if the format of the string stays like this. Here's an idea.
console.log(`[2022/07/12, 2022/08/09]`
.slice(1, -1)
.split(`, `));
Or edit to create a valid JSON string:
const dateArray = JSON.parse(
`[2022/07/12, 2022/08/09]`
.replace(/\[/, `["`)
.replace(/\]/, `"]`)
.replace(/, /g, `", "`));
console.log(dateArray);
Or indeed use the match method #Barmar supplied.
const regexp = /\d+\/\d+\/\d+/g;
const stringarr = "[2022/07/12, 2022/08/09]";
const arr = [...stringarr.matchAll(regexp)];
console.log(arr)
It's to much simple 😄.
As your input is a valid array in string format. So, remove [ ] brackets and split with comma (,). Then it automatically generates an array.
let stringarr = "[2022/07/12, 2022/08/09]";
let arr = stringarr.replace(/(\[|\])/g, '').split(',');
Output:
['2022/07/12', ' 2022/08/09']
Related
I am learning JavaScript , the fundamentals for now and what I don’t get, is how to count the characters in the string in order to use the slice on the certain string and extract a certain word out of the string.
For example
let text = "JavaScript", "apples", "avocado");
let newText = text.slice(?),(?);
How do I know or count the position of apples for example or JavaScript?
Thank you!
Try like this:
let text = "JavaScript, apples, avocado";
let newText = text.slice(text.indexOf("JavaScript"));
let newText2 = text.slice(text.indexOf("apples"));
console.log(newText)
console.log(newText2)
Few observations/suggestions :
String will always wrapped with the quotes but in your post it is not looks like a string.
Why you want to slice to get the word from that string ? You can convert that string into an array and then get that word.
Implementation steps :
Split string and convert that in an array using String.split() method.
Now we can find for the word you want to search from an array using Array.find() method.
Working Demo :
// Input string
const text = "JavaScript, apples, avocado";
const searchText = 'apples';
// Split string and convert that in an array using String.split() method.
const splittedStringArray = text.split(',');
// Now we can find for the word from splittedStringArray using Array.find() method.
const result = splittedStringArray.find(item => item.trim() === searchText);
// Output
console.log(result);
split the string into an array, , and then splice in the string you do want. Finally, join the array elements into a new string.
const str = 'JavaScript, apples, avocado';
function replace(str, search, replacement) {
// Create an array using `split`
const arr = str.split(', ');
// Find the index of the item you're looking for
const index = arr.findIndex(el => el === search);
// `splice` in the new replacement string
arr.splice(index, 1, replacement);
// Return the new string
return arr.join(', ');
}
console.log(replace(str, 'apples', 'biscuit'));
I have couple of strings like this:
Mar18L7
Oct13H0L7
I need to grab the string like:
Mar18
Oct13H0
Could any one please help on this using JavaScript? How can I split the string at the particular character?
Many Thanks in advance.
For var str = 'Mar18L7';
Try any of these:
str.substr(0, str.indexOf('L7'));
str.split('L7')[0]
str.slice(0, str.indexOf('L7'))
str.replace('L7', '')
Based on input that is given it I have created following function which can take n string in array and return the output in the format you have given. Check if this helps and if some use case is missed.
function generateStr(arr, splitStr) {
const processedStr = arr.map(value => value.split(splitStr)[0]);
return processedStr.join(" OR ");
}
console.log(generateStr(["Mar18L7", "Oct13H0L7"], "L7"));
You can use a regex like this
var data = ["Mar18L7", "Oct13H0L7"];
var regex = /^([a-zA-Z0-9]+)\L[a-zA-Z0-9]+$/;
var output = []
data.forEach(function(el){
var matches = el.match(regex);
output.push(matches[1]);
});
output variable will be equal to ['Mar18', 'Oct13H0'] and you can join all value usin the .join method on output array
var chain = output.join(" OR ");
// chain will be equal to "Mar18 OR Oct13H0"
I would like to capture the array key from a string.
Here are my words: message[0][generic][0][elements][0][default_action][url]...
I want to capture the array keys after message[0][generic][0][elements][0], and the expected results are default_action and url etc.
I have tried following patterns but not work.
message\[0\]\[generic\]\[0\]\[elements\]\[0\](?=\[(\w+)\]): it captures default_action only;
\[(\w+)\]: it captures all array keys, but includes 0, generic, elements...
Is there any regex pattern for JavaScript that make the result array inverse, like [url, default_action]?
You can replace unwanted part of a string,and then get all other keys.
var string = 'message[0][generic][0][elements][0][default_action][url][imthird]';
var regexp = /message\[0\]\[generic\]\[0\]\[elements\]\[0\]/
var answer = string.replace(regexp,'').match(/[^\[\]]+/g)
console.log(answer);
To extract any number of keys and reverse the order of the elements in resulting array:
str = "message[0][generic][0][elements][0][default_action][url]";
res = str.match(/\[([^\d\]]+)\](?=\[[^\d\]]*\]|$)/g)
.map(function(s) { return s.replace(/[\[\]]/g, "") })
.reverse();
console.log(res);
The solution using String.prototype.split() and Array.prototype.slice() functions:
var s = 'message[0][generic][0][elements][0][default_action][url]...',
result = s.split(/\]\[|[\[\]]/g).slice(-3,-1);
console.log(result);
In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)
Javascript:
var string = '(37.961523, -79.40918)';
//remove brackets: replace or regex? + remove whitespaces
array = string.split(',');
var split_1 = array[0];
var split_2 = array[1];
Output:
var split_1 = '37.961523';
var split_2 = '-79.40918';
Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?
Use
string.slice(1, -1).split(", ");
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
You would probably like to use regular expressions in a case like this:
str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]
EDIT Fixed to address issue pointed out in comment below
Here is another approach:
If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:
str = str.replace('(', '[').replace(')', ']')
Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:
var coordinates = JSON.parse(str);