I have an input Json string like this:
var x= "[{\"name\":\"ahmed\",\"age\":\"26\"},
{\"name\":\"Sam\",\"age\":\"25\"}]"
I want to split it to a list of strings from{ to } as follows without removing a delimiter
var list;
list[0]= {\"name\":\"ahmed\",\"age\":\"26\"}
list[1]= {\"name\":\"Sam\",\"age\":\"25\"}
using the split method removes the delimiter and does not yield the correct format
x= x.replace(/\[\/]/g, '/'); //to remove [ and ]
x= x.replace( /},/ ,'}\n' ); // does not split the string to list of strings
list = x; // type mismatch error since x is a string and list is array
As commented above by Teemu, using JSON.parse is the safe and correct way to parse json.
const x = "[{\"name\":\"ahmed\",\"age\":\"26\"},{\"name\":\"Sam\",\"age\":\"25\"}]";
console.log(JSON.parse(x));
You can parse it to JSON first then use map to make list out of it.
var parsedX = JSON.parse(x);
var list = parsedX.map(x => JSON.stringify(x).replace(/"/g,'\\"'));
You could use following code to achieve desired result with this particular type of json:
var str = "[{\"name\":\"ahmed\",\"age\":\"26\"}, {\"name\":\"Sam\",\"age\":\"25\"}]";
var list = str.match(/[{][^{}]*[}]/gm);
alert(list)
Fell free to ask if you have any questions:
Related
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
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 have an string like'[[br,1,4,12],[f,3]]'. I want to split as strings and integers and put it into array like the string [['br',1,4,12],[f,3]].string maybe like '[]' or '[[cl,2]]',ect...but the words only,br,cl,fand i. How does get the array. Any idea for this problem?
Thanks
You can do conversion that you wanted by using RegEx :
Get your string
var str = '[[br,1,4,12],[f,3]]';
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
console.log(str);
//Outputs :
[["brd",1,4,12],["f",3]] // It is still just a string
If you wanted to convert it to object, you might use this :
var str = '[[br,1,4,12],[f,3]]';
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var obj = toJSObject(str);
I want to covert this string to jquery data table. I can't do this.
var str = "96,xxx,212,xxxx||
100,yyy,123,yyyy";
My original DataSet structure like this
var aDataSet = [['96','xxx','212','xxxx'],
['100','yyy','123','yyyy']];
This is my code what i tried;
var srchvalue = str.split('||');
for (var e = 0; e < srchvalue.length; e++) {
alert(srchvalue[e]);
aDataSet.push(srchvalue[e]);
}
But it's not convert the actual format.
You will just need to split() twice. You've done the first bit already. Then you will need to split the two strings in your array with the , as the separator.
You can use aDataSet.push(srchvalue[e].split(',')) inside the for loop you already have.
You are pushing in your array the result of a split on "||" which is a series of string like "96,xxx,212,xxxx". You need to split that string too in order to have a matrix:
[...]
aDataSet.push(srchvalue[e].split(','));
[...]
I got the solution, I used the below code to convert it.
var test = eval('[' + srchvalue[e].split(',') + ']');
aDataSet.push(test);
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);