Getting second last occurrence and capturing the string after that - javascript

I have the following url string as a example
https://jsonplaceholder.typicode.com/todos/101/'
I want to store 101 so I can use that part of string in some other logic. I tried the following.
const filter = (value)=>{
return value.split("/").pop();
})
but it returns empty, from what I know, as pop(), pop off last but and last bit is only / and nothing after that.
How can I modify my code to give me the value after the second to last /

If you're not sure if there will be a trailing slash, you can use filter to remove all empty elements, and then pop the '101':
const filter = value => value.split('/').filter(i => i).pop()
console.log(filter('https://jsonplaceholder.typicode.com/todos/101/'))
console.log(filter('https://jsonplaceholder.typicode.com/todos/101'))
filter(i => i) simply loops over each item in the array to see if it evaluates to true, so all falsy items like '' or undefined will be removed.

When you split, the last / gets split as an empty string, which you receive when you pop(). If we remove it before splitting you will get the result you want.
You could do this oneliner
value.slice(0, -1).split('/').pop();

Because the URL ends in the delimiter you're splitting on, the last item in the resulting array will be the empty string, and the second-to-last item will be the match you're looking for. You can .pop() twice:
const filter = (value)=>{
const splits = value.split('/');
splits.pop();
return splits.pop();
};
Or you could use a regular expression to match non-/ characters, followed by / and the end of the string::
const filter = value => value.match(/[^\/]+(?=\/$)/)[0];
console.log(filter('https://jsonplaceholder.typicode.com/todos/101/'))

You can extract the number before the last '/' as follows.
const url = 'https://jsonplaceholder.typicode.com/todos/101/';
const filter = value => {
let segments = value.split('/');
return segments[ segments.length -2];
}
console.log(filter(url));

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

generate two variables while using split

I have a string like this
test/something/else
I would like to generate two variables
first = test
second = something/else
I tried with
const [first, ...second] = "test/something/else".split("/");
and it gives me the right value for first but for second it's an array. So I have to join the array to get the value I need?
Use a regular expression to match a (single) / followed by anything, so that the result is the 2 strings you want:
const str = 'test/something/else';
const [, first, second] = str.match(/([^/]+)\/(.*)/);
console.log(first);
console.log(second);
If you had to use split, and you don't want the extra array, you can do something similar by putting the second part into a capture group:
const str = 'test/something/else';
const [first, second] = str.split(/\/(.*)/);
console.log(first);
console.log(second);
Correct, the idiomatic built-in command to do this is to .split() and then .join(‘’) the tail elements.
It may be (very slightly) faster to check for the index and slice the string with that, something like
function splitAt(str, delimiter) {
const idx = str.indexOf(delimiter);
const head = str.slice(0, idx);
const tail = str.slice(idx);
return [head, tail];
}
Solution is simple, we should take 2 variables, in one variable assign the string which includes '/' then in another variable assign split method split(//(.*)/) with expresion and console log it
var str = "how r u?/kkk/jj";
const [first, second] = str.split(/\/(.*)/);
console.log(first);
console.log(second);
split method break the string and assign em to arrays. The string will be break after '/' and whenever console log the item, the broken string will be displayed.

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

Categories