Javascript Regular expression capture - javascript

I'm sure there might be something simular on stack overflow but I can't find anything and am getting quite frustrated with what should be very simple.
I need to capture part of a url (similar to a url rewriting engine) using javascript.
URL structure:
http://example.com/constant/CAPTURETHIS
http://example.com/constant/CAPTURETHIS/
http://example.com/constant/CAPTURETHIS#noise
http://example.com/constant/CAPTURETHIS/#noise
I need to just return the CAPTURETHIS text for all 3 senerios

JavaScript supports the retrieval of regex capture-groups by using a string object's match method or a regular-expression object's exec method:
var captureThis = url.match(/^http:[/][/]example[.]com[/]constant[/]([^/]+)/)[1];
var captureThis = /^http:[/][/]example[.]com[/]constant[/]([^/]+)/.exec(url)[1];
But for your example, I almost wonder if it's simpler to use the string object's split method:
var captureThis = url.split(/[/]/)[4];

Related

Getting query string from re written URL

I have url "SampleProject/profile/aA12". How can I get the value of the id from my rewritten URL using javascript? I want to get the "aA12" value.
Im using htaccess rewrite to rewrite my URL. Im new in rewritting url's. Any help will be appreciated. More powers and thank you.
You can use regex.
Try
'SampleProject/profile/aA12'.match(/\SampleProject\/profile\/(\w+)/)
'SampleProject/profile/aA12/xxx'.match(/\SampleProject\/profile\/(\w+)/)
'aA12' will be matched in both cases.
There are going to be quite a few ways to achieve your goal with JavaScript. A simple solution could be something like this:
let myURL = "SampleProject/profile/aA12";
let result = myURL.split('/').pop();
// returns "aA12"
The .split('/') method is dividing your string up into an array using the / character, and .pop() is simply returning the last element of that array.
Hope this helps! If you were looking for more advanced matching, i.e. if you wanted to ignore a potential query string on the end of the URL parameter, you could use regular expressions.
Their is a many way that you can use to achieve the desired method i made you a code pen in this link
var url = "SampleProject/profile/aA12";
let res = url.split('/').pop();
console.log(res)
https://codepen.io/anon/pen/KQxNja

How to get the domain name using regular expression in javascript?

I have just started to use regular expression and I am finding it difficult to find a regular expression to get the main domain name, that is, if I have urls as given below..
url = http://blog.example.co.in/page/category=?order.php
url = https://www.example.co.ca?page.html
so out of this I want to get only the example out the urls given above. So how can i do it..!!If you can get example in any other method will also be helpful..
I myself tried some methods as given below..
var url = urls.replace('http://','').replace('https://','').replace('www.','').split(/[/?#]/)[0];
var out = url.split('.')[0];
in this I am able to get the output for
https://www.example.co.ca?page.html
but not for
url = http://blog.example.co.in/page/category=?order.php
so can someone help me out a method that can get example out of any kind url
thank you

Javascript regex match doesn't run correctly

okay I give up. Here's my code:
var re = /href="(http.*\.jpg)"/g;
var mp3s = body.match(re);
it finds pictures, but it returns href="http://www.picture.com/smthg.jpg"
instead of returning http://www.picture.com/smthg.jpg
any idea why?
The result from match() is actually an object.
I think you need to access the first element on that object.
For example:
body.match(re)[1]
This is where the actual result is kept.
Shameless self-promotion:
I've written a small guide for me, I can never remember how to use these either. It's here: http://queirozf.com/reminders/javascript-regular-expressions-usage-reminder
try
var re = /(http.*\.jpg)/g;
var mp3s = body.match(re);
since you don't need the href.
You want to match the regular expression, but then return just the portion in brackets.
To do this, call the regular expressions exec method. For example:
var body = 'stuff stuff morestuff href="http://www.picture.com/smthg.jpg" and some more stuff';
var re = /href="(http.*\.jpg)"/g;
var regexResults = re.exec(body);
var mp3s = regexResults[1];
alert(mp3s);
Having given you this answer, I must implore you to find a different way to solve this problem. You cannot parse HTML using regular expressions. No matter how sophisticated your regular expression gets, there will be a legal HTML example which will break it.

How to extract a javascript variable using regular expression

I need to extract a javascript variable containing a multiline JSON from a remote page using a python script(2.7), and I want to use regex to do this, but my pattern does not return anything
What am I doing wrong ?
here's my code :
request = urllib2.Request("http://somesite.com/affiliates/")
result = urllib2.urlopen(request)
affiliates = re.findall('#var affiliates = (.*?);\s*$#m', result.read())
print affiliates
If you look at the docs for re.findall(pattern, string, flags=0), you'll see you need to change how you're using it
affiliates = re.findall('var affiliates = (.*?);\s*$', result.read(), re.M)
You might also want to consider how whitespace can be sloppy in JavaScript.

Use Regex in Javascript to get the filename in a URL

I'm using JavaScript to try and get the filename from the URL.
I can get it using this:
var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array
but is there an easier way to get it (e.g., without having to use fn[fn.length-1]
Thanks!!
Add a $ at the end so you only get the last part:
window.location.href.match(/[^/]+$/g);
Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
Or simply:
var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
Additional Information
Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name
How about:
window.location.href.match(/\/([^/]+)$/)[1];
you can use .pop() to get the last element of an array;
alert(fn.pop());
There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:
https://github.com/allmarkedup/jQuery-URL-Parser
I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.
I recommend to also remove any '#' or '?' string, so my answer is:
var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);
split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string

Categories