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.
Related
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
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));
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.
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
When I utilise the slice method like so:
"Hello".slice(0,-1);
The result I get will be "Hell". Then if I run through that again using the same code, I will get "Hel".
Is there a way that I can extract and store into a variable the actual character that was sliced off, in this case "H" or on the second run "e", and not just the remainder of the string?
You could just use a second .slice() on the original string.
For example, where "Hello".slice(0,-1); returns all but the last character, "Hello".slice(-1) returns only the last character.
var input = "Hello";
var removed = input.slice(-1); // "o"
var remaining = input.slice(0, -1); // "Hell"
I don't think there's a more generic solution than that, because .slice() also lets you extract the middle of a string, in which case you'd need two extra calls to get the two parts being removed.
Demo:
var input = "Hello";
var allRemoved = [];
var removed;
while (input != "") {
allRemoved.push(removed = input.slice(-1));
input = input.slice(0, -1);
console.log("'" + removed + "' removed, leaving '" + input + "'");
}
console.log("Removed: " + allRemoved.join(", "));
Alternatively, if you only care about removing characters one at a time, you could forget about .slice() and instead convert the string to an array and use .shift() or .pop() to remove the character at the beginning or end respectively:
var input = "Hello";
var inArr = input.split("");
while (inArr.length > 0) {
console.log(inArr.pop());
}
This might not be the most efficient way to do this but you can turn yout string as an array with .split, then use .splice to remove certain elements ( letters ) and store them as a variable. Finally you turn your variable of removed letters back to a string using .join
let name = 'David'
let arrayname = name.split('')
let chosenLetters = arrayname.splice(0,2)
let finalLetters = chosenLetters.join('')
console.log(finalLetters) //should output Da
For split and join I recommend you leave the argument as (''). For .splice you can find in the docs for js how to select specific letters. In my example I am saying "Start at index 0 and cut the first 2 elements". Splice has many other ways to select an index so I recommend you read the docs.
In one line of code it can be generalized to :
let name = 'David'
let finalLetters = name.split('').splice(0,2).join('')
console.log(finalLetters) //should output Da