javascript split string function not working - javascript

I am trying to split a string:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = device_data.split('*');
But it's not working. it's just displaying this string
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = str.split('*');
console.dir(res)
,HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#,HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555
Instead of creating an array with two elements.

IMHO, you want something like this:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
splitStrArr = str.split('*').filter(str => str != "")
console.log(splitStrArr)
console.log(splitStrArr[0])
console.log(splitStrArr[1])

You are getting a string with a period in the beginning because whatever you are doing leads to the result of String#split being converted to a string. String#split returns an array. An array converted to a string is of the form of element0,element1,element2 ... elements separated by commas.
The result of String#split in your case is ["",...] with 3 elements since your string begins with the character '*' you are searching, so String#split will create an empty string as the first element of the returned array. So the result is exactly as expected, and String#split is working as intended.
get rid of the first character of the string,
mystring.substr(1).split('*')
get rid of the empty strings
mystring.split('*').filter(s=>s!='')
to obtain the desired result.

You can use:
var res = str.split("#");
You can check in Javascript console in browser itself.
As a suggestion/ idea, you can always use the browser console, for example, Chrome browser, to execute simple scripts like these.
This way, you can save time, as it is easier to check your data structures, their internal data.

If you try
var res = str.split('*');
you obtain three elements:
res[0] is '' (empty string)
res[1] is 'HQ,61...'
res[2] is 'HQ,...'

Related

Splitting String and taking out specific elements in node js

I have Sample String like this
"Organisation/Guest/images/guestImage.jpg"
I need to take out Organisation,Guest separately.
I have tried split() but can't get desired output.
var str = "Organisation/Guest/images/guestImage.jpg";
var res = str.split("/");
console.log(res[0]);
console.log(res[1]);
You can use of String.replace() along with regex
const regex = /Organisation\/|\/Organisation/;
console.log('Organisation/Guest/images/guestImage.jpg'.replace(regex, ''));
console.log('Guest/Organisation/images/guestImage.jpg'.replace(regex, ''));
console.log('Guest/images/guestImage.jpg/Organisation'.replace(regex, ''));
var yourString = "Organisation/Guest/images/guestImage.jpg";
yourString.split('/')
// this returns all the words in an array
yourString[0] // returns Organisation
yourString[1] // returns Guest and so on
When you run .split() on a string, it will return a new array with all the words in it. In the code I am splitting by the slash /
Then I save the new array in a variable. Now you should know we can access array properties like this: array[0] where 0 is the first index position or the first word, and so on.

Why is JavaScript's split() method not splitting on ":"?

So to start off, a bit of context. I am pulling data from the following url: "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all" using a GET method. The data returned is a series of Pokemon names and image names in the following format.
Name1:name1.png
Name2:name2.png
...
The list is 151 items long. When I call the typeOf() method "String" is returned, so I am fairly certain it is a String I am dealing with here. What I would like to do is split the String on the delimiters of "\n" and ":".
What I would like:
Name1,name1.png,Name2,name2.png...
After some experimentation with Regex, I found that the Regex to do this was "\n|:". Using this I wrote the following line to split the String apart. I tested this Regex on https://regex101.com and it seems to work properly there.
var splitData = data.split("\n|:");
("data" is the String I receive from the url.)
But instead of splitting the String and placing the substrings into an array it doesn't do anything. (At least as far as I can see.) As such my next idea was to try replacing the characters that were giving me trouble with another character and then splitting on that new character.
data = data.replace("\n", " ");
data = data.replace("/:/g", " ");
var splitData = data.split(" ");
The first line that replaces new line characters does work, but the second line to replace the ":" does not seem to do anything. So I end up with an array that is filled with Strings that look like this.
Name1:name1.png
I can split these strings by calling their index and then splitting the substring stored within, which only confuses me more.
data = data.replace("\n", " ");
var splitData = data.split(" ");
alert(splitData[0].split(":")[1]);
The above code returns "name1.png".
Am I missing something regarding the split() method? Is my Regex wrong? Is there a better way to achieve what I am attempting to do?
Right now you are splitting on the string literal "\n|:" but to do a regex you want data.split(/[:\n]/)
The MDN page shows two ways to build a Regex:
var regex1 = /\w+/;
var regex2 = new RegExp('\\w+');
The following test script was able to work for me. I decided to use the regex in the split instead of trying to replace tokens in the string. It seemed to do the trick for me.
let testResponse = `Abra:abra.png
Aerodactyl:aerodactyl.png`;
let dataArray = testResponse.split(/\n|:/g);
let commaSeperated = dataArray.join(',');
console.log(commaSeperated);
So you can simply use regex by excluding the quotes all together.
You can look at the documentation here for regular expressions. They give the following examples:
var re = /ab+c/;
var re = new RegExp('ab+c');
See below for your expected output:
var data = `Name1:name1.png
Name2:name2.png`;
var splitData = data.split(/[\n:]/);
console.log(splitData);
//Join them by a comma to get all results
console.log(splitData.join(','));
//For some nice key value pairs, you can reduce the array into an object:
var kvps = data.split("\n").reduce((res, line) => {
var split = line.split(':');
return {
...res,
[split[0]]: split[1]
};
}, {});
console.log(kvps);
I tried and this works good.
str.split(/[:\n]/)
Here is a plunker.
plunker

JavaScript regular Expression to extract a substring which is in double qoutes, from a master string

i have a string , which look like an array of strings. I need a regex pattern in javascript to extract the substrings inside that master string, and return me the substring. Look at the string given below, and i need a regex on the basis of this string. And the regex will extract the substrings like :
files/file/img1.jpg ,files/file/img2.jpg and so on, until the end. As much directories i have , i want them to be extracted. For time being just consider that its not an array, its just a string. Thank you
str =
"["files/file/img1.jpg","files/file/img2.jpg","files/file/img3.jpg","files/file/img4.jpg","files/file/img5.jpg","files/file/img6.jpg"] ";
Use JSON.parse to parse your string.Then just iterate over the array.
var str =
'["files/file/img1.jpg","files/file/img2.jpg","files/file/img3.jpg","files/file/img4.jpg","files/file/img5.jpg","files/file/img6.jpg"]';
var result = JSON.parse(str);
for(var i= 0; i< result.length;i++){
console.log(result[i]);
}
The syntax is kinda wrong. It should be:
var str ="[\"files/file/img1.jpg\",\"files/file/img2.jpg\",\"files/file/img3.jpg\",\"files/file/img4.jpg\",\"files/file/img5.jpg\",\"files/file/img6.jpg\"] ";
Apart from that we can just use multiple Javascript string manipulation functions to extract the string:
data = str.split('["')[1].split('"]')[0].replace(/"/g, "").split(',');
Now the variable data is an array which has all the directories you need. The output looks something like this:
(6) ["files/file/img1.jpg", "files/file/img2.jpg", "files/file/img3.jpg", "files/file/img4.jpg", "files/file/img5.jpg", "files/file/img6.jpg"]
You can get each directory by indexing it: data[0] is the first one.

String split returns an array with more elements than expected (empty elements)

I don't understand this behaviour:
var string = 'a,b,c,d,e:10.';
var array = string.split ('.');
I expect this:
console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1
but I get this:
console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2
Why two elements are returned instead of one? How does split work?
Is there another way to do this?
You could add a filter to exclude the empty string.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});
A slightly easier version of #xdazz version for excluding empty strings (using ES6 arrow function):
var array = string.split('.').filter(x => x);
This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.
If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Use String.split() method with Array.filter() method.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);
console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
trim the trailing period first
'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
then split the string
var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
console.log (array.length); // 1
That's because the string ends with the . character - the second item of the array is empty.
If the string won't contain . at all, you will have the desired one item array.
The split() method works like this as far as I can explain in simple words:
Look for the given string to split by in the given string. If not found, return one item array with the whole string.
If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
In case the given string starts with the string to split by, the first item of the result array will be empty.
In case the given string ends with the string to split by, the last item of the result array will be empty.
It's explained more technically here, it's pretty much the same for all browsers.
According to MDN web docs:
Note: When the string is empty, split() returns an array containing
one empty string, rather than an empty array. If the string and
separator are both empty strings, an empty array is returned.
const myString = '';
const splits = myString.split();
console.log(splits);
// ↪ [""]
Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.
Because your string is composed of 2 part :
1 : a,b,c,d,e:10
2 : empty
If you try without the dot at the end :
var string = 'a,b,c:10';
var array = string.split ('.');
output is :
["a,b,c:10"]
You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.
So, this behavior is normal. What did you want to achieve by using this string.split?
try this
javascript gives two arrays by split function, then
var Val = "abc#gmail.com";
var mail = Val.split('#');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Categories

Resources