Count the elements in string - javascript

I have a string that has comma separated values. How can I count how many elements in the string separated by comma?
e.g following string has 4 elements
string = "1,2,3,4";

myString.split(',').length

var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;

All of the answers suggesting something equivalent to myString.split(',').length could lead to incorrect results because:
"".split(',').length == 1
An empty string is not what you may want to consider a list of 1 item.
A more intuitive, yet still succinct implementation would be:
myString.split(',').filter((i) => i.length).length
This doesn't consider 0-character strings as elements in the list.
"".split(',').filter((i) => i.length).length
0
"1".split(',').filter((i) => i.length).length
1
"1,2,3".split(',').filter((i) => i.length).length
3
",,,,,".split(',').filter((i) => i.length).length
0

First split it, and then count the items in the array. Like this:
"1,2,3,4".split(/,/).length;

First You need to convert the string to an array using split, then get the length of the array as a count, Desired Code here.
var string = "1,2,3,4";
var desiredCount = string.split(',').length;

Related

How can I create a Regex that only lets in comma separated numbers?

I want my user to be able to add multiple numeric values separated by commas. For example,
Allowed Strings
1,2,3
.1,2.0,3.,
Not Allowed
1,,2..3
1,2,.,3,.
I have this so far:
/(\.?)(\d+)(,?)/g
As a bonus, I would also like to have the regex that I could give to the JS match method which will give me an array of the values entered by the user.
You can use a function that will split the string by the comas and then check if every items are numbers (!isNaN) to decide to return the splitted string (an array) or something else.
const allowed_1 = "1,2,3"
const allowed_2 = ".1,2.0,3.,"
const notAllowed_1 = "1,,2..3"
const notAllowed_2 = "1,2,.,3,."
const checkNumbers = (string) => {
items = string.split(",")
return items.every((item) => !isNaN(item)) ? items : "Not allowed"
}
console.log(checkNumbers(allowed_1))
console.log(checkNumbers(allowed_2))
console.log(checkNumbers(notAllowed_1))
console.log(checkNumbers(notAllowed_2))
^(((\d*\.?\d+)|(\d+\.?\d*))(,)|((\d*\.?\d+)|(\d+\.?\d*)))+$
^((\d+\.?\d*,?)|(\d+\.?\d+,?)|(\d*\.?\d+)(,?))+$
edit: thanks to #Brooke because my 1st answer had an error, now this one should work perfectly
edit2: the 2dn one is more understandable

How to get a substring in between 2 identical characters in javascript?

So I know how to get a substring from 2 characters using index or split method. But I'm stuck in a scenario of lots of string with similar names such as:
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something"
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something"
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else"
Like I am stuck on how to extract just the "mission#" part, because sometimes the names can be different, so the length is different, and sometimes the names are the same, same as the fileName. I also thought about using the index of "_", but there are multiple "_" and they might end up in different index if the name is different.
Could anyone give me some hint on this?
If the structure of the strings are always the same - and you want the second instance of 'mision' - then split the full string on the text of 'mission'.
This will yield an array with three portions -
["2020-12-09-name_of_this_", "num1", "1_fileName_something"])
Then get the last item in this portions array and grab the number from the start of the resultant string.
Then you can prefix it with the 'mission' that you removed, push it into an array and you have a array of of missions.
If your initial string does not contain a two instances of 'mission' then you can set it to return the 2nd not 3rd portion as I have doen with 'mission2'.
const missions = [
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something",
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something",
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else",
"2020-12-09-name_of_this_mission2_fileName_something_else"
]
let missionsArr = [];
missions.forEach(function(mission) {
const missionPortions = mission.split('mission');
let index;
missionPortions.length == 2
? index = 1
: index = 2
missionsArr.push('mission' + parseInt(missionPortions[index]))
})
console.log(missionsArr); //gives ["mission1","mission12", "mission1", "mission2"];
A simple regex match function. Note that 'match' outputs an array, so push match[0]:
const missions = [
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something",
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something",
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else"
]
let Arr = [];
missions.forEach(function(mission) {
const missionID = mission.match(/mission\d+/);
Arr.push(missionID[0]);
})
console.log(Arr);
Easiest way to just get the mission##, assuming # is a variable number of digits, is by using regex.
The base regex would be /mission\d+/ which matches the string "mission" followed by at least one number.
Assuming you have your input as:
const missionsTexts = [
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something",
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something",
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else"
];
You can transform them into an array of just mission# with the following algorithm:
const missions = missionsTexts.map(missionText => missionText.match(/mission\d+/g)[0]);
Note that this assumes there's only one mission# per missionText. The g modifier is used to make sure the regex doesn't create a match after the first digit it finds.

Getting all the strings that start with "_" and end in 10 random characters JavaScript

I have this array:
Array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23]
I want all the values that start with "_" and are followed by 10 random characters.
So the return in this instance would be
Array = ["_B07TLNWCSV","_A674598385","_U8965H456NV"]
How would I do this in Javascript?
UPDATE
Say If I want to get all the elements on a webpage that follow the same rule,
On a webpage the element is like so:
<tr id="_B07TLNWCSV">data</tr>
how would I get all table row elements that follow the rule "_(10 RANDOM CHARS)"
I understand that querySelectorAll which get all the elements that follow the rule but I can't get it working.
Use Array.filter(), filtering words that start with _ and have a 11 chars length ( _ + 10 chars )
const array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23"];
const result = array.filter(word => word.startsWith('_') && word.length === 11);
console.log(result);
Here is a simple code that you might looking for.
Hope my code would be useful!
const array=["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23", "_123456789123"];
let newArray=[];
array.forEach(function(word){
if(word.length==11&&word[0]=="_") newArray.push(word);
});
console.log(newArray);
You just need to use filter() along with hardcoded index [0] and string length 11.
const array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23"];
const result = array.filter((f) => { return f[0] === '_' && f.length === 11 });
console.log(result);
You can use the filter() method and a regular expression for this:
var array = ["rubbish3","_B07TLNWCSV","_A674598385","_U8965H456NV","crapcrap","crapcrap23"];
var filteredArray = array.filter(function(elem) {
return elem.match(/^_.{10}$/);
});
console.log(filteredArray);
Explanation of the regular expression:
^_ => the string must start with a _.
.{10} => then we must have ten characters (. means any character)
$ => end of string, i.e. the string must stop there, we can't have any more characters.
Edit: Regarding your question update, the simplest way to target these elements is to add a common class name to all of them, say:
<tr id="_B07TLNWCSV" class="data">data</tr>
<tr id="_B07TLNWDSA" class="data">data</tr>
<tr id="_B07TLNWCXB" class="data">data</tr>
And then use getElementsByClassName("data") to retrieve the elements.

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 convert an array of strings to float in Javascript

I have this array and it is formatted as string:
['6.35', '2.72', '11.79', '183.25']
The problem is that when I convert it to numbers (using - without double quotes )
array.match(/\d+/g).map(Number) || 0;
it changes the dots used for decimals to commas. Then I end up with this new array:
6,35,2,72,11,79,183,25
So, instead of having 4 items inside the array, now I have 8 items, as my delimiters are commas.
Any ideas of how I can convert this array without replacing the dots?
Assuming you have an array in a string format, you can use the following regex to match all the decimals and then use .map(Number)
const str = "['6.35', '2.72', '11.79', '183.25']",
array = str.match(/\d+(?:\.\d+)?/g).map(Number)
console.log(array)
\d matches only digits, it's the short for [0-9]. For example, in 6.35 \d+ matches 6 and then 35 separately and the dot is ignored. What you get in result is array containing those matches.
As suggested in other answers, use of match is redundant in your case and you can go with:
array.map(Number)
You could just map numbers.
var array = ['6.35', '2.72', '11.79', '183.25'],
numbers = array.map(Number);
console.log(numbers);
var num = ['6.35', '2.72', '11.79', '183.25'].map(num => Number(num));
console.log(num);
Number() mdn
Parse the values to float :
console.log(['6.35', '2.72', '11.79', '183.25'].map(i => parseFloat(i)));
If for some reason .map() doesn't work just use a loop :
var array = ['6.35', '2.72', '11.79', '183.25']
var x = 0;
var len = array.length
while(x < len){
array[x] = parseFloat(array[x]);
x++
}
console.log(array)
Map over the array with the Number function, it will handle the conversion:
console.log(['6.35', '2.72', '11.79', '183.25'].map(Number));
If you want commas in your numbers, then you must stick with a string representation.
See this SO answer about a similar problem with ChartJS.
var arr = ["6,35,2,72,11,79,183,25"]
var result=arr.map(Number);
result[]
typeof(result[])
I was having the same problem this is a solution i found
i had
x = "11,1.1,100,100,2,3333,99"
and i wanted
x = [11,1.1,100,100,2,3333,99]
here's my solution
x.toString().replace(/, +/g, ",").split(",").map(Number)

Categories