Unable to get numbers from window.location.search - javascript

I am using the following code in my JS file:
var match = window.location.search.match(/(\d*)/);
this.room = (match) ? decodeURIComponent(match) : 0;
And I am trying to just get the numbers from my URL. For example, in www.myurl.com/streams228, I just want to get the 228.
The issue I am getting is it is just returning %2, nothing else, or 0.

Try the following:
var url ="www.myurl.com/streams228"
var match = url.match(/([\d]+)/g);
console.log(match[0]);

Try to match the pathname. The search refers to the query string.
window.location.pathname.match(/(\d*)/)

After using the code above from everyone I did this
var match = window.location.pathname.match(/([\d]+)/g);
this.room = (match && match[0]) ? decodeURIComponent(match[0]) : 0;
and it works perfectly.
Thanks

Related

regex: get string in url login/test

I have a url
https://test.com/login/param2
how do I get the the second parameter "param2" from the url using REGEX?
the url can also be
https://test.com/login/param2/
So the regex should work for both urls.
I tried
var loc = window.location.href;
var locParts = loc.split('/');
and then looping through locParts, but that seems inefficient.
The "param2" can be have number, alphatical character from a-z, and a dash.
Use String#match method with regex /[^\/]+(?=\/?$)/.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var reg = /[^\/]+(?=\/?$)/;
console.log(
a.match(reg)[0],
b.match(reg)[0]
)
Or using String#split get last non-empty element.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var splita = a.split('/'),
splitb = b.split('/');
console.log(
splita.pop() || splita.pop(),
splitb.pop() || splitb.pop()
)
If you don't mind using JS only (so no regex), you can use this :
var lastParameter = window.location.href.split('/').slice(-1);
Basicaly, like you, I fetch the URL, split by the / character, but then I use the splice function to get teh last element of the split result array.
Regular expressions might be compact, but they're certainly not automatically efficient if you can do what you want without.
Here's how you can change your code:
var loc = 'https://test.com/login/facebook/'; // window.location.href;
var locParts = loc.split('/').filter(function(str) {return !!str});
var faceBookText = locParts.pop();
console.log(faceBookText);
The filter removes the last empty item you would get if the url ends with '/'. That's all you need, then just take the last item.

How get domain from string?

var string = "https://example.com/app/something";
var string = "example.com/app/something";
new URL(string.origin)
If string have protocol all ok, and if not. have error Failed to construct 'URL': Invalid URL(…)
How can I obtain the root domain without using regex?
The question is still a bit unclear, and I'm not entirely sure how you're getting that string, but just for the sake of argument, here's a quick solution:
function getHostname(str)
{
str = (/^\w+:\/\//.test(str) ? "" : "http://") + str
return new URL(str).hostname;
}
console.log(getHostname("https://example.com/app/something"));
console.log(getHostname("example.com/app/something"));
Yes, technically, this technically does use a regular expression to check if the protocol is present, but it uses the URL class actually parse the host name.
Regex example:
var example1 = "www.example1.com/test/path";
var example2 = "https://example2.com/test/path";
var example3 = "http://subdomain.example3.com/test/path";
function getDomain(str) {
var matches = str.match(/^(?:https?:\/\/)?((?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6})/);
if (!matches || matches.length < 2) return '';
return matches[1];
}
console.log(getDomain(example1));
console.log(getDomain(example2));
console.log(getDomain(example3));
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
http://regexr.com/
If I understand your question correctly, you want to check if the URL contains either the http or https protocol. This can easily be done with string functions built into JavaScript as shown below.
var string = window.location;
if (string.includes('http') || string.includes('https'))
{
//Do your logic here
}
UPDATE: Alternatively, you could use substring functionality shown below.
var string = window.location;
if (string.indexOf('http') == 0)
{
//Do your logic here
}
Note that this will also verify that the http is at the beginning of the string and not just thrown in willy nilly.

Remove hash from current page’s URL

I want to remove the hash, as well as anything after it, from a URL. For example, I might have:
http://example.com/#question_1
… which slides to question no. 1 to show an error message. When the user’s input then passes validation, I need to remove #question_1 from the current location.
I’ve tried all of these, but none of them has worked for me:
document.location.href.replace(location.hash, "");
window.location.hash.split('#')[0];
window.location.hash.substr(0, window.location.hash.indexOf('#'));
Note: I don’t just want to get the URL – I want to remove it from my address bar.
history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )
Try this :use .split() to split string by # and then read first element in array using index 0
var url = 'http://example.com#question_1';
var urlWithoutHash = url.split('#')[0];
alert(urlWithoutHash );
Use split in javascript
var str = "http://example.com#question_1";
alert(str.split("#")[0]);
Try this way:
var currentPath = window.location.pathname;
var myUrl = currentPath.split("#")[0];
OR
var currentPath = window.location.href;
var myUrl = currentPath.split("#")[0];
Hope it helps.
This will clear the id selector from the uri
location.hash = '';
Use .split as shown :
var str = "http://example.com#question_1";
alert((str.split("#")[0]);
or use .substring() as shown :
var str = "http://example.com#question_1";
alert((str.substring(0,str.indexOf('#'))));

Find and replace string with dot in javascript

I want to find and replace a part of string if present in string.
String is like '1.png,2.png,3.jpg,4.gif'
I want find 1.png in this string and then replace it if exist with 1.jpg.
I am not able to find it using search() and indexOf() method.
and since i am not able to find it i cannot replace it.
I am trying this way
var str = '1.png'
var new_str = '1.jpg'
var main_str = '1.png,2.png,3.jpg,4.gif';
if(main_str.indexOf(str) > 0){
alert('found')
// now replace it with new_str
}
else{
alert('not found')
}
I have tried following combination but these are not working.
main_str.indexOf('str') > 0
main_str.indexOf(/\str/) > 0
main_str.indexOf(/\"str"/) > 0
main_str.indexOf(str) > 0
Please see and suggest any possible way to do this.
Thanks
The index of 1.png in your string is actually 0, that is why your condition fails. Correct way is to check whether index is not negative, since indexOf returns -1 if substring is not found:
if(main_str.indexOf(str) >= 0){
but even better approach here is to use replace:
main_str.replace(str, new_str)
Since the main_str contains 1.png at index 0, you can never find it with the check main_str.indexOf('str') > 0. Remeber that javascript returns -1 if not found and not zero. So you'll have to update your condition to:
main_str.indexOf('str') != -1
try,
var str="1.png,2.png,3.jpg,4.gif";
var newStr=str.replace(".png",".jpg");
you can use the replace method:
var str = '1.png,2.png,3.jpg,4.gif';
var result=str.replace('1.png','1.jpg')
You can do the replacement using replace :
main_str = main_str.replace(str, new_str)
If you want to replace more than one occurrence, use
main_str = main_str.replace(new RegExp(str,'g'), new_str)
If you want to alert before replacing, do this :
var r = new RegExp(str,'g');
if (main_str.match(r)) {
alert('found')
main_str = main_str.replace(r, new_str)
} else {
alert('not found')
}
you can do this:
var str = "1.png,2.png,3.jpg,4.gif";
var re = /(.png)/i;
var found = str.match(re);
//now ask the user or do whatever else is needed
if (found){
found = confirm("Really overwrite");
}
if (found){
str = str.replace(re, ".jpg");
}
I allow in the string now also upper case or mixed case, like ".Png" or ".PNG"

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

Categories

Resources