Convert a string of array into array javascript - javascript

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)

Related

Convert a string of an array to an array js

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']

How to take value using regular expressions?

I have such a string "Categ=All&Search=Jucs&Kin=LUU".How to get an array of values from this line [All,Jucs,LUU].
Here is an example
let x = /(\b\w+)$|(\b\w+)\b&/g;
let y = "Categories=All&Search=Filus";
console.log(y.match(x));
but I wanted no character &.
Since this looks like a URL query string, you can treat it as one and parse the data without needing a regex.
let query = "Categ=All&Search=Jucs&Kin=LUU",
parser = new URLSearchParams(query),
values = [];
parser.forEach(function(v, k){
values.push(v);
});
console.log(values);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Note: This may not work in IE, if that's something you care about.
Loop through all matches and take only the first group, ignoring the =
let x = /=([^&]+)/g;
let y = "Categories=All&Search=Filus";
let match;
while (match = x.exec(y)) {
console.log(match[1]);
}
To achieve expected result, use below option of using split and filter with index to separate Keys and values
1. Use split([^A-Za-z0-9]) to split string based on any special character other letters and numbers
2. Use Filter and index to get even or odd elements of array for keys and values
var str1 = "Categ=All&Search=Jucs&Kin=LUU";
function splitter(str, index){
return str.split(/[^A-Za-z0-9]/).filter((v,i)=>i%2=== index);
}
console.log(splitter(str1, 0)) //["Categ", "Search", "Kin"]
console.log(splitter(str1, 1))//["All", "Jucs", "LUU"]
codepen - https://codepen.io/nagasai/pen/yWMYwz?editors=1010

How to get the string just before specific character in JavaScript?

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"

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

Javascript: String of text to array of characters

I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
The split() method is used to split a string into an array of
substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is
split between each character.
Note: The split() method does not change the original string.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);

Categories