Convert string to Jquery dataset - javascript

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);

Related

Split a string into a list of strings

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:

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"

How to use split in javascript

I have a string like
/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content
I want only /abc/def/hij part of string how do I do that.
I tried using .split() but did not get any solution.
If you want to remove the particular string /lmn.o, you can use replace function, like this
console.log(data.replace("/lmn.o", ""));
# /abc/def/hij
If you want to remove the last part after the /, you can do this
console.log("/" + data.split("/").slice(1, -1).join("/"));
# /abc/def/hij
you can do
var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");
Alternatively:
var dirname = str.split("/").slice(0, -1).join("/");
See the benchmarks
Using javascript
var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");
after this, use
arr.pop();
to remove the last content of the array which would be lmn.o, after which you can use
var new_s= arr.join("/");
to get /abc/def/hij

JavaScript split and add a string

how to insert a string inside the url address after split ?
I have a simple code like this, but I just don't understand how split and join are work
I have tried "append" function but I can't get it right
I test and write it in
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_split
<html>
<body>
<script type="text/javascript">
var str="/image/picture.jpg";
var test = str.split("/");
for(var i = 0; i < test.length; i++) {
document.write(test[1].join('/original') + "<br />");
}
document.write(test);
</script>
</body>
the output that I want is simply like this :
"/image/original/picture.jpg"
note: thanks for the help.
Just use replace instead:
str.replace('image/', 'image/original/');
if you really want to convert it into an array for some reason:
var ary = str.split('/');
ary.splice(2, 0, 'original');
ary.join('/');
vikenoshi,
You want to use the Array.splice method to insert new elements into your resulting array that you created using String.split. The splice method is documented here:
http://www.w3schools.com/jsref/jsref_splice.asp
Here is the code which should do what you want:
function spliceTest() {
var url = "/image/picture.jpg";
// split out all elements of the path.
var splitResult = url.split("/");
// Add "original" at index 2.
splitResult.splice(2, 0, "original");
// Create the final URL by joining all of the elements of the array
// into a string.
var finalUrl = splitResult.join("/");
alert(finalUrl); // alerts "/image/original/picture.jpg"
};
I created a JsFiddle with a working example:
http://jsfiddle.net/S2Axt/3/
A note about the other methods I'm using:
join: Join creates a new string from an array. This string is constructed by transforming all of the elements of the array into a string, and appending or concatenating them together. You can optionally provide a delimitter. Here I use the / to split the portions of the path.
split: Split splits a string based on another string into an array.
You could also do this:
var wholeURL = "/image/picture.jpg";
var choppedUpURL = wholeURL.split("/");
var finalURL = "/" + choppedUpURL[1] + "/original/" + choppedUpURL[2];
alert(finalURL);
http://jsfiddle.net/jasongennaro/KLZUT/
It's quick and simple
var str="/image/picture.jpg";
var elems = str.split("/");
elems.splice(elems.length-1, 0, "original")
document.write(elems.join("/");
Note I'm using the splice method with a first argument of the length of the array - 1. This puts the string "original" in the second to last position in the final path, not matter how long the URL you pass in. If this isn't the desired behavior, you can change the code to read elems.splice(2, 0, "original"). This would put the string "original" in the second position in the path, no matter how long the URL is.
Part of the problem with your code is that you're calling join on a string, not an array, see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join.
The return type of split is an array, https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split. So doing
var test = str.split("/");
means that test is an array. So then test[1] is a string of that array, and calling join on it won't work.
try:
var str="/image/picture.jpg";
var test = str.split("/");
test[3]=test[2];
test[2]='original';
document.write(test.join('/'));

JavaScript split function

i like to split a string depending on "," character using JavaScript
example
var mystring="1=name1,2=name2,3=name3";
need output like this
1=name1
2=name2
3=name3
var list = mystring.split(',');
Now you have an array with ['1=name1', '2=name2', '3=name3']
If you then want to output it all separated by spaces you can do:
var spaces = list.join("\n");
Of course, if that's really the ultimate goal, you could also just replace commas with spaces:
var spaces = mystring.replace(/,/g, "\n");
(Edit: Your original post didn't have your intended output in a code block, so I thought you were after spaces. Fortunately, the same techniques work to get multiple lines.)
Just use string.split() like this:
var mystring="1=name1,2=name2,3=name3";
var arr = mystring.split(','); //array of ["1=name1", "2=name2", "3=name3"]
If you the want string version of result (unclear from your question), call .join() like this:
var newstring = arr.join(' '); //(though replace would do it this example)
Or loop though, etc:
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
You can play with it a bit here

Categories