Add comma after each number in an array - javascript

I'm trying to create a simple page that prompts the user for an input and checks a list to see if that input is included and will then return a true or false answer to the user. At the moment it is working fine and the code looks like this:
var barcodes = [
123425245,
62753264574,
1878769047,
00000000000001718075,
302,
303,
];
var entry=prompt("enter barcode");
var num1=parseInt(entry);
document.write(barcodes.includes(num1));
My problem is that I have over 2000 items to add to this array and I am trying to copy and paste them in from an excel spreadsheet. When I copy them in there is no comma separating each barcode and therefore i'm getting an error message. Is there a quick way to add commas at the end of each number in the array or do I have to do it manually?
Thanks for any help

As from Docs:
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
You can create an array using split() by splitting your data like this:
let str = "123425245 62753264574 1878769047 00000000000001718075 302 303";
let barcodes = str.split(" ").map(Number);
console.log(barcodes);

var barcodes = [
123425245,
62753264574,
1878769047,
00000000000001718075,
302,
303,
];
var temp = barcodes.join(",");
console.log(temp)

Related

search text in array using regex in javascript

I am very new to making search text in array some elements in array are in rangers i.e it cant be anything after certain text in this AA and A regex and I have multi-dimensional array and I want search text in each array . So I wrote something like this.I put AA* in array so only first 2 character should match and A* for only one character match.
arr = [
["AA*","ABC","XYZ"] ,
["A*","AXY","AAJ"]
]
var text = "AA3";
for ($i=0; $i<arr.length; $i++ ){
var new_array = [];
new_array = arr[$i];
new_array.filter(function(array_element) {
var result = new RegExp(array_element).test(text);
if( result == true){
console.log(arr[$i]);
}
});
}
So what i want is when text = "AA3" or anything after double A AA[anything] and the output should be first array which is ["AA*","ABC","XYZ"] but I am getting both array as output and when text = "A3" then output should be second array which is ["A*","POI","LKJ"] but I am getting both array.But if text = "ABC" or text = "AAJ" then it should output first array or second array respectively.I dont know anything about how to write regex or is there anyway I can implement this using any other method.
Thanks in advance any advice will be helpful.
Summary
In short, the issue is "*"! The * found in the members of the set array is why you're getting the same array each time.
Detailed Info
Regexp is a one concept most developers find hard to understand (I am one of such btw 😅).
I'll start off with an excerpt intro to Regexp on MDN
Regexp are patterns used to match character combinations in strings - MDN
With that in mind you want to understand what goes on with your code.
When you create a Regex like /A*/ to test "AA3", what would be matched would be A, AA, etc. This is a truthy in javascript. You would want a more stricter matching with ^ or $ or strictly matching a number with \d.
I rewrote your code as a function below:
arr = [
["AA*", "ABC", "XYZ"],
["A*", "AXY", "AAJ"],
];
findInArray(arr, "AA3") // prints both array
findInArray(arr, "AAJ") // prints second array
findInArray(arr, "ABC") // prints first array
function findInArray(array, value) {
return array.filter((subArray) =>
subArray.some((item) => {
const check = new RegExp(value);
return check.test(item);
})
);
}
Problem
The problem lies in the fact you use each of the strings as a regex.
For a string with a * wildcard, this evaluates to zero or more matches of the immediately preceding item, which will always be true.
For a string consisting solely of alphanumerics, this is comparing a string to itself, which similarly will always give true.
For strings containing characters that constitute the regex's syntax definition, this could result in errors or unintended behavior.
MDN article on RegExp quantifiers
Rewrite
Assumptions:
The value with a * wildcard is always only at the 0th position,
There is only one such wildcard in its string,
The question mentions that for text = 'AAJ' only the 2nd array shall be returned, but both the AA* from the 1st array and AAJ from the 2nd would seem to match this text.
As such, I assume the wildcard can only stand for a number (as other examples seem to suggest).
Code:
const abc = (arrs, text) => {
return arrs.filter(arr => {
const regex = new RegExp(`^${arr[0].replace('*', '\\d+')}$`);
return regex.test(text) || arr.includes(text);
})
}
const arr = [
["AA*", "ABC", "XYZ"],
["A*", "AXY", "AAJ"]
];
console.log(
`1=[${abc(arr, "AA3")}]
2=[${abc(arr, "ABC")}]
3=[${abc(arr, "AAJ")}]`);

javascript split string function not working

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,...'

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

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

convert url encoded data to JSON array or js array

How can I convert data that looks like it is url encoded to a JSON array or js array.
&nfl_s_delay=120&nfl_s_stamp=1109033755&nfl_s_left1=Cleveland%2024%20%20%20Cincinnati%203%20(END%20OF%204TH)&nfl_s_right1_count=0&nfl_s_url1=http://sports.espn.go.com/nfl/boxscore?gameId=400554328&nfl_s_left2=Kansas%20City%2017%20%20%20Buffalo%2013%20(00:00%20IN%204TH)&nfl_s_right2_count=0&nfl_s_url2=http://sports.espn.go.com/nfl/boxscore?gameId=400554332&nfl_s_left3=Miami%2016%20%20%20Detroit%2020%20(00:00%20IN%204TH)&nfl_s_right3_count=0&nfl_s_url3=http://sports.espn.go.com/nfl/boxscore?gameId=400554355&nfl_s_left4=^Dallas%2031%20%20%20Jacksonville%2017%20(FINAL)&nfl_s_right4_count=0&nfl_s_url4=http://sports.espn.go.com/nfl/boxscore?gameId=400554358&nfl_s_left5=San%20Francisco%2027%20%20%20New%20Orleans%2024%20(END%20OF%201ST%20OT)&nfl_s_right5_count=0&nfl_s_url5=http://sports.espn.go.com/nfl/boxscore?gameId=400554362&nfl_s_left6=Tennessee%207%20%20%20Baltimore%2021%20(00:00%20IN%204TH)&nfl_s_right6_count=0&nfl_s_url6=http://sports.espn.go.com/nfl/boxscore?gameId=400554367&nfl_s_left7=Pittsburgh%2013%20%20%20NY%20Jets%2020%20(END%20OF%204TH)&nfl_s_right7_count=0&nfl_s_url7=http://sports.espn.go.com/nfl/boxscore?gameId=400554370&nfl_s_left8=Atlanta%2027%20%20%20Tampa%20Bay%2017%20(END%20OF%204TH)&nfl_s_right8_count=0&nfl_s_url8=http://sports.espn.go.com/nfl/boxscore?gameId=400554372&nfl_s_left9=Denver%2041%20%20%20Oakland%2010%20(00:00%20IN%203RD)&nfl_s_right9_count=0&nfl_s_url9=http://sports.espn.go.com/nfl/boxscore?gameId=400554396&nfl_s_left10=St.%20Louis%2014%20%20%20Arizona%2010%20(00:00%20IN%202ND)&nfl_s_right10_count=0&nfl_s_url10=http://sports.espn.go.com/nfl/boxscore?gameId=400554397&nfl_s_left11=NY%20Giants%2017%20%20%20Seattle%2017%20(00:00%20IN%203RD)&nfl_s_right11_count=0&nfl_s_url11=http://sports.espn.go.com/nfl/boxscore?gameId=400554400&nfl_s_left12=Chicago%20at%20Green%20Bay%20(8:30%20PM%20ET)&nfl_s_right12_count=0&nfl_s_url12=http://sports.espn.go.com/nfl/preview?gameId=400554403&nfl_s_left13=Carolina%20at%20Philadelphia%20(8:30%20PM%20ET)&nfl_s_right13_count=0&nfl_s_url13=http://sports.espn.go.com/nfl/preview?gameId=400554408&nfl_s_count=13&nfl_s_loaded=true
I would split split by &nfl_s_left2= , but the parameter increases by one for each time. So I could split by &nfl_s_left2= but that would only split once as the next thing that is similar is &nfl_s_left3= . So I guess a more specific question is can I split by a variable string?
I could split by &nfl_s_left but then I'd get the number= in the value of the array.
What would be the best way I could clean up this data?
how about this
function url_split(str){
var jsArry={},tmp = str.split('&nfl_s_'),tmp2;
tmp.forEach(function(e){
tmp2 = e.split('=');
jsArry[tmp2[0]] = tmp2[1];
});
return jsArry;
}
and the fiddle demo http://jsfiddle.net/oswspkL0/

Categories

Resources