Javascript and Regex tuning - striping string - javascript

From the URL:
https://www.flightstats.com/v2/historical-flight/TP/1478/2020/11/3/1047614176
I need to get "2020/11/3"
WHAT I HAVE
The Regex:
\d\/(\d+\/\d+\/\d+)
it returns: for full match - "8/2020/1/3", for Group 1 - "2020/1/3". I've tested several combinations and tried to simplify it till this version
The Javascript:
var myRe = /\d\/(\d+\/\d+\/\d+)/;
var myArray = myRe.exec('${initialurl}');
Being initialurl a variable
PROBLEMS
The javascript returns: "8/2020/11/3,2020/11/3" and I only need/want the group 1 match or if the full match is correct, just that.
CONTEXT
Javascript newbie
I'm using this in Ui.Vision Kantu

If your URLs are going to reliably be in the format shown then this would do it:
\d{4}\/\d{1,2}\/\d{1,2}
https://regex101.com/r/BqW2lr/1
var initialurl = 'https://www.flightstats.com/v2/historical-flight/TP/1478/2020/11/3/1047614176';
var myRe = /\d{4}\/\d{1,2}\/\d{1,2}/;
var myArray = myRe.exec(initialurl);
console.log(myArray);

Related

JavaScript regex to search between strings

Hi I would like to search between strings using regex for JavaScript
String format:
saobjectid=tt-234,ou=info
saobjectid=bb-456,ou=info
saobjectid=bng,ou=info
saobjectid=asx 1 ert 7,ou=info
Expected output:
tt-234
bb-456
bng
asx 1 ert 7
I have tried this
[a-z]+[-,\s]+[0-9]+
But didn't manage to capture all different scenarios
Thanks for your help
Just added this answer to depict that it can also be done using substr in javascript:
var a = "saobjectid=tt-234,ou=info";
var b = "saobjectid=bb-456,ou=info";
var c = "saobjectid=bng,ou=info";
var d = "saobjectid=asx 1 ert 7,ou=info";
console.log(getSubstr(a));
console.log(getSubstr(b));
console.log(getSubstr(c));
console.log(getSubstr(d));
function getSubstr(a){
return a.substr(a.indexOf('=')+1, a.indexOf(',') - a.indexOf('=')-1);
};
a regex like =([-\s\w]+), will do.
Check it out at regex101 or here:
var s=`saobjectid=tt-234,ou=info
saobjectid=bb-456,ou=info
saobjectid=bng,ou=info
saobjectid=asx 1 ert 7,ou=info"`;
var regexp = /=([-\s\w]+),/g;
while ((match = regexp.exec(s)) != null){
console.log(match[1]);
}

Javascript extract only the capturing group

I need to extract an id from a string but I can't only the ID. I'm trying to user a pattern that works fine in Java, but in JS it yields more results than I like. Here is my code:
var reg = new RegExp("&topic=([0-9]+)");
When applying execute this against the string "#p=activity-feed&topic=1697"
var results = reg.exec("#p=activity-feed&topic=1697");
I was hoping to get just the number part (1697, in this case) because this was preceded by "&topic=", but this is returning two matches:
0: "&topic=1697"
1: "1697"
Can someone help me to get ["1967","9999"] from the string "#p=activity-feed&topic=1697&no_match=1111&topic=9999"?
Assuming the browser support is right for your use case, URLSearchParams can do all of the parsing for you:
var params = new URLSearchParams('p=activity-feed&topic=1697&no_match=1111&topic=9999');
console.log(params.getAll('topic'));
While Noah's answer is arguably more robust and flexible, here's a regex-based solution:
var topicRegex = /&topic=(\d+)/g; // note the g flag
var results = [];
var testString = "p=activity-feed&topic=1697&no_match=1111&topic=9999";
var match;
while (match = reg.exec(testString)) {
results.push(match[1]); // indexing at 1 pulls capture result
}
console.log(results); // ["1697", "9999"]
Works for any arbitrary number of matches or position(s) in the string. Note that the matches are still strings, if you want to treat them as numbers you'll have to do something like:
var numberized = results.map(Number);

Most efficient way to extract parts of string

I have a bunch of strings in the format 'TYPE_1_VARIABLE_NAME'.
The goal is to get 3 variables in the form of:
varType = 'TYPE',
varNumber = '1',
varName = 'VARIABLE_NAME'
What's the most efficient way of achieving this?
I know I can use:
var firstUnderscore = str.indexOf('_')
varType = str.slice(0, firstUnderscore))
varNumber = str.slice(firstUnderscore+1,firstUnderscore+2)
varName = str.slice(firstUnderscore+3)
but this feels like a poor way of doing it. Is there a better way? RegEx?
Or should I just rename the variable to 'TYPE_1_variableName' and do a:
varArray = str.split('_')
and then get them with:
varType = varArray[0],
varNumber = varArray[1],
varName = varArray[2]
Any help appreciated. jQuery also ok.
Regex solution
Given that the first and second underscores are the delimiters, this regex approach will extract the parts (allowing underscores in the last part):
//input data
var string = 'TYPE_1_VARIABLE_NAME';
//extract parts using .match()
var parts = string.match(/([^_]+)_([^_]+)_([^$]+)/);
//indexes 1 through 3 contains the parts
var varType = parts[1];
var varNumber = parts[2];
var varName = parts[3];
Given that the first variable consists of characters and the second of digits, this more specific regex could be used instead:
var parts = string.match(/(\w+)_(\d)_(.+)/);
Non-regex solution
Using .split('_'), you could do this:
//input data
var string = 'TYPE_1_VARIABLE_NAME';
//extract parts using .split()
var parts = string.split('_');
//indexes 0 and 1 contain the first parts
//the rest of the parts array contains the last part
var varType = parts[0];
var varNumber = parts[1];
var varName = parts.slice(2).join('_');
In matters of efficiency, both approaches contain about the same amount of code.
You could use regex and split
var string='TYPE_1_VARIABLE_NAME';
var div=string.split(/^([A-Z]+)_(\d+)_(\w+)$/);
console.log('type:'+div[1]);
console.log('num:'+div[2]);
console.log('name:'+div[3]);
Here's an answer I found here:
var array = str.split('_'),
type = array[0], number = array[1], name = array[2];
ES6 standardises destructuring assignment, which allows you to do what Firefox has supported for quite a while now:
var [type, number, name] = str.split('_');
You can check browser support using Kangax's compatibility table.
Here's a sample Fiddle

Get the second last parameter in a url using javascript

I have a url like this
http://example.com/param1/param2/param3
Please help me get the second last parameter using javascript. I searched and could only find regex method to find the last parameter. I am new to this. Any help would be greatly appreciated.
Thanks.
var url = 'http://example.com/param1/param2/param3';
var result= url.split('/');
var Param = result[result.length-2];
Demo Fiddle:http://jsfiddle.net/HApnB/
Split() - Splits the string into an array of strings based on the separator you mentioned
In the above , result will be an array that contains
result = [http:,,example.com,param1,param2,param3];
Basic string operations:
> 'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
"param2"
You can do this by:
document.URL.split("/");
var url='http://example.com/param1/param2/param3';
var arr = url.split('/');
alert(arr[arr.length-2]);
arr[arr.length-2] will contain value 'param2'. Second last value
var url = "http://example.com/param1/param2/param3";
var params = url.replace(/^http:\/\/,'').split('/'); // beware of the doubleslash
var secondlast = params[params.length-2]; // check for length!!
var url = "http://example.com/param1/param2/param3";
var split = url.split("/");
alert(split[split.length - 2]);
Demo: http://jsfiddle.net/gE7TW/
The -2 is to make sure you always get the second last
My favorite answer is the following from #Blender
'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
However all answers suffer from the edge case syndrome. Below are the results of applying the above to a number of variants of your input string:
"http://example.com/param1/param2/param3" ==> "param2"
"http://example.com/param1/param2" ==> "param1"
"http://example.com/param1/" ==> "param1"
"http://example.com/param1" ==> "example.com"
"http://example.com" ==> ""
"http://" ==> ""
"http" ==> "http"
Note in particular the cases of the trailing /, the case with only // and the case with no /
Whether these edge cases are acceptable is something you will need to determine within the larger context of your code.
Do not validate this answer, choose from amongst the others.
Just another alternate solution:
var a = document.createElement('a');
a.href = 'http://example.com/param1/param2/param3'
var path = a.pathname;
// get array of params in path
var params = path.replace(/^\/+|\/+$/g, '').split('/');
// gets second from last parameter; returns undefined if not array;
var pop = params.slice(-2)[0];

Regex: capture everything until specific word(s)

I have two variations of a string something like :
The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115
Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 9781280117268
Now, I want to grab the first Author: Alcock, Pete aand Saran, Pooranachandra.
Now in Javascript, I am trying to do :
var regex = new RegExp("(Author:)\\s(.+)(?=;|MIL)");
var regexVal = value.match(regex);
console.log(regexVal);
OR
var regex = new RegExp("(Author:)\\s(.+)(?=MIL)");
var regexVal = value.match(regex);
console.log(regexVal);
Second Regex works perfectly fine if there is one Author, however, in case of multiple author, I want to pick value until first ; not MIL
| matched either part, so, shouldn't it stop when first ; is found?
Regards,
Ravish
You could use:
var regex = /Author:\s([^;*]+)/;
Or if those * aren't in the string:
var regex = /Author:\s((?:(?!MIL)[^;])+)/;
or
var regex = /Author:\s([^;])+?)(?=;|MIL)/;
Solved my problem by modifying the regex to :
(Author:)(([^;])+)(;|MIL)
This regex says : should begin with "Author:" neget the ; and should end with ; or MIL.
Thanks

Categories