Regex - Match a string between second occurance of characters - javascript

I have a string of text that looks something like this:
?q=search&something=that&this=example/
In that example, I need to grab that . I'm using the following regex below:
var re = new RegExp("\&(.*?)\&");
Which going re[1] is giving me:
something=that - but it needs to be only that
I tried:
var re = new RegExp("\=(.*?)\&");
But that gives me everything from the first equals sign, so:
search&something=that
Is the output when it just needs to be:
that
I need to somehow target the second occurrences of 2 characters and grab whats in between them. How best do I go about this?

You can use
/something=([^&]+)/
and take the first group, see the JavaScript example:
let url = '?q=search&something=that&this=example/';
let regex = /something=([^&]+)/
let match = regex.exec(url);
console.log(match[1]);

split seems more suited to your case:
"?q=search&something=that&this=example/".split("&")[1].split("=")[1]
Then you could also implement a simple method to extract any wanted value :
function getValue(query, index) {
const obj = query.split("&")[index];
if(obj) obj.split("=")[1]
}
getValue("?q=search&something=that&this=example/", 1);

Related

How can I add two hyphens in an RegEx expression?

I have a value that I will want to add two hyphens.
For example, if I receive:
FN322KN
I want to transform it to:
FN-322-KN
I am trying to use this solution (Mask javascript variable value) and Im stuck here:
CODE:
var value = 'FN322KN';
var formatted = value.replace(/^(.{2})(.{5}).*/, '$1-$2');
RESULT KO:
'FN-322KN'
Can someone please tell me how I can add the second "-" ?
UPDATE!!
Both Mark Baijens and Buttered_Toast answers are correct. I have one more question though. What if the value comes like FN-322KN or F-N322-KN ? Like, out of format? Because if thats the case, then it adds one hifen where one already exists, making it "--".
Thanks!
Assuming you always want the hyphens after the first 2 characters and after the first 5 characters you can change the regex easily to 3 groups.
var value = 'FN322KN';
var formatted = value.replace(/^(.{2})(.{3})(.{2}).*/, '$1-$2-$3');
console.log(formatted);
Going by the provided content you have, you could try this
(?=(.{5}|.{2})$)
https://regex101.com/r/JZVivU/1
const regex = /(?=(.{5}|.{2})$)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?=(.{5}|.{2})$)', 'gm')
const str = `FN322KN`;
const subst = `-`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

JS: Remove all text to the left of certain last character with Regex

I'm trying to remove all the text which falls before the last character in a Regex pattern.
Example:
rom.com/run/login.php
Becomes:
login.php
How would I go about doing this in JavaScript? I'm new to regular expressions.
To get everything after last slash, use [^\/]+$
const str = "rom.com/run/login.php";
console.log(str.match(/[^/]+$/)[0]);
You can get the result you need by searching for a literal string (just one character in fact) so there's no need to employ regular expressions which will cost you performance.
You can split the input into chunks separated by / and get the last chunk:
var input = 'rom.com/run/login.php';
var result = input.split('/').pop();
Or find the position of the last occurrence of / in the input, and get the remainder of the string that follows that position:
var input = 'rom.com/run/login.php';
var result = input.substring(input.lastIndexOf('/') + 1);
One approach is a regex replacement:
var path = "rom.com/run/login.php";
var output = path.replace(/^.*\//, "");
console.log(output);
The regex pattern ^.*/ is greedy, and will consume everything up to (and including) the last path separator. Then, we replace this match with empty string, to effectively remove it.
You could do it with Regex like this:
var url = 'rom.com/run/login.php'
var page = url.match('^.*/(.*)')[1]
console.log(page)
Or you could do it without Regex like this:
var url = 'rom.com/run/login.php'
var split = url.split('/')
var page = split[split.length-1]
console.log(page)

Regex to match path like /^String1(anything)(String2 or String3)/

For example:
String1: Books>Programming>
String2: Databases>
String3: Languages>
Anything: ''
is matched by the following regex:
/^Books>Programming>(Databases>|Languages>)/
Now, let's say Anything is not empty, e.g. "whatever1>", how should the regex change?
I tried with lookaround but no luck, I may be missing something obvious.
If I got you corectly you want to match path like Books>Programming>[anything]>(Databases> | Languages>). If so you can do it like this.
let String1 = "Books>Programming>",
String2 = "Databases>",
String3 = "Languages>"
let regex = new RegExp(`${String1}(.*?)>(?:${String2}|${String3})`)
Benefit of this method is that you can modify variables at will and create modified regex while executing your code so it's not hard-coded.
Now if you want to test if string matches this pattern you can use:
regex.test("Books>Programming>whatever1>Databases>")
And if you want to extrat whatever1 from this just use:
"Books>Programming>abc>Databases>".match(regex)[1]
You can use String.prototype.split to acheive that without the use of regular expressions. Like this:
function getParts(str) {
var parts = str.split(">"); // split the string by ">"
if(!parts[parts.length - 1].length) // if the last part is empty
parts.pop(); // remove it
return parts; // return the array of the parts (ordered by default)
}
console.log(getParts("Something>Books>Another thing>Programming>"));

javascript, regex parse string content in curly brackets

i am new to regex. I am trying to parse all contents inside curly brackets in a string. I looked up this post as a reference and did exactly as one of the answers suggest, however the result is unexpected.
Here is what i did
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/
regex.exec(abc) // i got ["{string1}", "string1"]
//where i am expecting ["string1", "string2"]
i think i am missing something, what am i doing wrong?
update
i was able to get it with /g for a global search
var regex = /{(.*?)}/g
abc.match(regex) //gives ["{string1}", "{string2}"]
how can i get the string w/o brackets?
"test/abcd{string1}test{string2}test".match(/[^{}]+(?=\})/g)
produces
["string1", "string2"]
It assumes that every } has a corresponding { before it and {...} sections do not nest. It will also not capture the content of empty {} sections.
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g
var matches;
while(matches = regex.exec(abc))
console.log(matches);
Try this:
var abc = "test/abcd{string1}test{string2}test" //any string
var regex = /{(.+?)}/g //g flag so the regex is global
abc.match(regex) //find every match
a good place to read about Regex in javascript is here, and a nice place to test is here
good luck!
Nothing wrong. But you'll need to look at your capturing groups (the second element in the array) to get the content you wanted (you can ignore the first). To get all occurences, it's not enough to run exec once, you'll need to loop over the results using match.
Edit: nevermind that, afaik you can't access capturing groups with match. A simpler solution would be using a positive lookahead, as Mike Samuel suggested.
This result:
["{string1}", "string1"]
is showing you that for the first match, the entire regex matched "{string1}" and the first capturing parentheses matched "string1".
If you want to get all matches and see all capturing parens of each match, you can use the "g" flag and loop through, calling exec() multiple times like this:
var abc = "test/abcd{string1}test{string2}test"; //any string
var regex = /{(.+?)}/g;
var match, results = [];
while (match = regex.exec(abc)) {
results.push(match[1]); // save first captured parens sub-match into results array
}
// results == ["string1", "string2"]
You can see it work here: http://jsfiddle.net/jfriend00/sapfm/
try this for file
const fs = require('fs');
fs.readFile('logs.txt', function(err, data) {
if(err) throw err;
const paragraph = "'" + data + "'";
const regex = /\d+\<;>\S+\<;>(\d+)\<;/g;
const found = paragraph.match(regex);
console.log(found);
})

Javascript Regexp - Match Characters after a certain phrase

I was wondering how to use a regexp to match a phrase that comes after a certain match. Like:
var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var match = /phrase=.*/;
That will match from the phrase= to the end of the string, but is it possible to get everything after the phrase= without having to modify a string?
You use capture groups (denoted by parenthesis).
When you execute the regex via match or exec function, the return an array consisting of the substrings captured by capture groups. You can then access what got captured via that array. E.g.:
var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var myRegexp = /phrase=(.*)/;
var match = myRegexp.exec(phrase);
alert(match[1]);
or
var arr = phrase.match(/phrase=(.*)/);
if (arr != null) { // Did it match?
alert(arr[1]);
}
phrase.match(/phrase=(.*)/)[1]
returns
"thisiswhatIwantmatched"
The brackets specify a so-called capture group. Contents of capture groups get put into the resulting array, starting from 1 (0 is the whole match).
It is not so hard, Just assume your context is :
const context = "https://example.com/pa/GIx89GdmkABJEAAA+AAAA";
And we wanna have the pattern after pa/, so use this code:
const pattern = context.match(/pa\/(.*)/)[1];
The first item include pa/, but for the grouping second item is without pa/, you can use each what you want.
Let try this, I hope it work
var p = /\b([\w|\W]+)\1+(\=)([\w|\W]+)\1+\b/;
console.log(p.test('case1 or AA=AA ilkjoi'));
console.log(p.test('case2 or AA=AB'));
console.log(p.test('case3 or 12=14'));
If you want to get value after the regex excluding the test phrase, use this:
/(?:phrase=)(.*)/
the result will be
0: "phrase=thisiswhatIwantmatched" //full match
1: "thisiswhatIwantmatched" //matching group

Categories