Regex returns string undefined - javascript

I am trying to extract hash value from an magnet link but it returns undefined
var tesst = "magnet:?xt=urn:btih:2B78EDFDDC87DC9605FB285997A80B787888C194&"
var test = tesst.match(/magnet:\?xt=urn:btih:[a-z\d]{40}\&/im);
alert (test[1]);
I cant understand what I am doing wrong.

var test = tesst.match(/magnet:\?xt=urn:btih:([a-z\d]{40})\&/im);
You forgot the ( ) around the hash part.

just mark what you want with capturing group:
/^magnet:\?xt=urn:btih:([a-z\d]{40})\&$/im
Also I recomend to not use regexp here.
Try followed:
tesst.split(':')[3].slice(0, -1);
slice(0, -1) used for remove last '&', you can use any other method, like slice(0, 40), replace(/[^\w]/g, '') or any other.

You need to include [a-z\d]{40} part inside a capturing group and you don't need to escape & symbol, because it isn't a regex meta character.
> var test = tesst.match(/magnet:\?xt=urn:btih:([a-z\d]{40})&/im);
undefined
> console.log(test[1])
2B78EDFDDC87DC9605FB285997A80B787888C194

You can use this regex
/([^:]+)&$/
and use test[1]
console.log(str.match(/([^:]+)&$/)[1]);

Related

remove all empty values from url string

I'm trying to remove all empty params from a url string. My url looks like this
http://localhost/wm/frontend/www/?test=&lol=1&boo=2
my code should return
http://localhost/wm/frontend/www/?lol=1&boo=2
but it doesn't instead it returns
http://localhost/wm/frontend/www/?&lol=1&boo=2
This is the regex i'm using replace("/(&?\w+=((?=$)|(?=&)))/g","") i know i could just use replace() strings that match '?&' after the 1st replace, but i would rather edit my regex to do so, so it's in 1 line of code. Any ideas?
here is my jsfiddle
You can use this regex for replacement:
/[^?&=]+=(?:&|$)|&[^?&=]+=(?=&|$)/g
And replace it by:
""
RegEx Demo
Try
/\w+=&|&\w+=$/g,
var url = "http://localhost/wm/frontend/www/?test=&lol=1&boo=2&j=";
document.write(url.replace(/\w+=&|&\w+=$/g, ""))
Just try to invoke native's 'replace', which could be used with a regex in its first argument.
str.replace(regex, replace_str)
Please, see this fiddle to see a running example: http://jsfiddle.net/xvqasgmu/1/
You can for example say:
var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');
That is, remove a block of letters + = + &. Then, remove & + letters + = at the end of the line (indicated by $).
For your input, it returns:
http://localhost/wm/frontend/www/?lol=1&boo=2
See it in JSFiddle or directly here:
var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');
document.write(s)
Test
If the input contains blocks in the middle and in the end:
http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=
the code I wrote above returns:
http://localhost/wm/frontend/www/?lol=1&boo=2

How to find in javascript with regular expression string from url?

Good evening, How can I find in javascript with regular expression string from url address for example i have url: http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/ and I need only string between last slashes (/ /) http://something.cz/something/string/ in this example word that i need is mikronebulizer. Thank you very much for you help.
You could use a regex match with a group.
Use this:
/([\w\-]+)\/$/.exec("http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/")[1];
Here's a jsfiddle showing it in action
This part: ([\w\-]+)
Means at least 1 or more of the set of alphanumeric, underscore and hyphen and use it as the first match group.
Followed by a /
And then finally the: $
Which means the line should end with this
The .exec() returns an array where the first value is the full match (IE: "mikronebulizer/") and then each match group after that.
So .exec()[1] returns your value: mikronebulizer
Simply:
url.match(/([^\/]*)\/$/);
Should do it.
If you want to match (optionally) without a trailing slash, use:
url.match(/([^\/]*)\/?$/);
See it in action here: http://regex101.com/r/cL3qG3
If you have the url provided, then you can do it this way:
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
var urlsplit = url.split('/');
var urlEnd = urlsplit[urlsplit.length- (urlsplit[urlsplit.length-1] == '' ? 2 : 1)];
This will match either everything after the last slash, if there's any content there, and otherwise, it will match the part between the second-last and the last slash.
Something else to consider - yes a pure RegEx approach might be easier (heck, and faster), but I wanted to include this simply to point out window.location.pathName.
function getLast(){
// Strip trailing slash if present
var path = window.location.pathname.replace(/\/$?/, '');
return path.split('/').pop();
}
Alternatively you could get using split:
var pieces = "http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/".split("/");
var lastSegment = pieces[pieces.length - 2];
// lastSegment == mikronebulizer
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
if (url.slice(-1)=="/") {
url = url.substr(0,url.length-1);
}
var lastSegment = url.split('/').pop();
document.write(lastSegment+"<br>");

Javascript replace one or another

I'm trying to make the replace function work when having one match or another. It's very simple as a logic so I'd like to have a very simple implementation.
I have tried:
var my_url = document.URL;
var tmpl = "?tmpl=component" || "&tmpl=component"; //This is the tricky part
location.href = my_url.replace(tmpl,"");
...but it doesn't seem to work. Any ideas please?
This is not how JavaScript works, logical OR is useless here. One possible way is using regex:
location.href = my_url.replace(/[?&]tmpl=component/, "");
Here the replace method will replace any match of tmpl=component starting with either ? or &.
You're setting tmpl to be the value of the expression "?tmpl=component" || "&tmpl=component";, which will always evaluate to "?tmpl=component", since it is the first truthy value in your or statement.
You can do this with regex in a number of ways:
my_url.replace(/?tmpl=component|&tmpl=component/, "");
my_url.replace(/[?&]tmpl=component/, "");
You could do two replacements:
location.href = my_url.replace("?tmpl=component", "").replace("&tmpl=component", "");
or you could use a regular expression: (recommended)
location.href = my_url.replace(/[?&]tmpl=component/, "");
[?&] will match either a '?' or '&' character.
Best one is:
var tmpl = (my_url.indexOf("?tmpl=component") > -1)? "?tmpl=component" : "&tmpl=component";

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

JavaScript match substring after RegExp

I have a string that look something like
something30-mr200
I would like to get everything after the mr (basically the # followed by mr) *always there is going to be the -mr
Any help will be appreciate it.
You can use a regexp like the one Bart gave you, but I suggest using match rather than replace, since in case a match is not found, the result is the entire string when using replace, while null when using match, which seems more logical. (as a general though).
Something like this would do the trick:
function getNumber(string) {
var matches = string.match(/-mr([0-9]+)/);
return matches[1];
}
console.log(getNumber("something30-mr200"));
var result = "something30-mr200".split("mr")[1];
or
var result = "something30-mr200".match(/mr(.*)/)[1];
Why not simply:
-mr(\d+)
Then getting the contents of the capture group?
What about:
function getNumber(input) { // rename with a meaningful name
var match = input.match(/^.*-mr(\d+)$/);
if (match) { // check if the input string matched the pattern
return match[1]; // get the capturing group
}
}
getNumber("something30-mr200"); // "200"
This may work for you:
// Perform the reg exp test
new RegExp(".*-mr(\d+)").test("something30-mr200");
// result will equal the value of the first subexpression
var result = RegExp.$1;
What about finding the position of -mr, then get the substring from there + 3?
It's not regex, but seems to work given your description?

Categories

Resources