Find and get only number in string - javascript

Please help me solve this strange situation:
Here is code:
The link is so - www.blablabla.ru#3
The regex is so:
var id = window.location.href.replace(/\D/, '' );
alert(id);
The regular expression is correct - it must show only numbers ... but it's not showing numbers :-(
Can you please advice me and provide some informations on how to get only numbers in the string ?
Thanks

You're replacing only the first non-digit character with empty string. Try using:
var id = window.location.href.replace(/\D+/g, '' ); alert(id);
(Notice the "global" flag at the end of regex).

Consider using location.hash - this holds just the hashtag on the end of the url: "#42".
You can write:
var id = location.hash.substring(1);

Edit: See Kobi's answer. If you really are using the hash part of things, just use location.hash! (To self: Doh!)
But I'll leave the below in case you're doing something more complex than your example suggests.
Original answer:
As the others have said, you've left out the global flag in your replacement. But I'm worried about the expression, it's really fragile. Consider: www.37signals.com#42: Your resulting numeric string will be 3742, which probably isn't what you want. Other examples: www.blablabla.ru/user/4#3 (43), www2.blablabla.ru#3 (23), ...
How 'bout:
id = window.location.href.match(/\#(\d+)/)[1];
...which gets you the contiguous set of digits immediately following the hash mark (or undefined if there aren't any).

Use the flag /\D/g, globally replace all the instances
var id = window.location.href.replace(/\D/g, '' );
alert(id);
And /\D+/ gets better performance than /\D/g, according to Justin Johnson, which I think because of \D+ can match and replace it in one shot.

Related

Removing elements of string before a specific repeated character in it in javascript

I'm trying to remove from my string all elements before an specific character which is repeated several times in this way:
let string = http://localhost:5000/contact-support
thus I´m just trying to remove everything before the third /
having as result:contact_support
for that i just set:
string.substring(string.indexOf('/') + 3);
Bust guess thats not the correct way
Any help about how to improve this in the simplest way please?
Thanks in advance!!!
It seems like you want to do some URL parsing here. JS brings the handful URL utility which can help you with this, and other similar tasks.
const myString = 'http://localhost:5000/contact-support';
const pathname = new URL(myString).pathname;
console.log(pathname); // outputs: /contact-support
// then you can also remove the first "/" character with `substring`
const whatIActuallyNeed = pathname.substring(1, pathname.length);
console.log(whatIActuallyNeed); // outputs: contact-support
Hope This will work
string.split("/")[3]
It will return the sub-string after the 3rd forward slash.
You could also use lastIndexOf('/'), like this:
string.substring(string.lastIndexOf('/') + 1);
Another possibility is regular expressions:
string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];
Note that you must escape the slash, since it is the delimiter in regular expressions.
string.substring(string.lastIndexOf('/')+1) will also do the job if you are looking to use indexOf function explicitly.

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

Is it possible to cut off the beginning of a string using regex?

I have a string which contains a path, such as
/foo/bar/baz/hello/world/bla.html
Now, I'd like to get everything from the second-last /, i.e. the result shall be
/world/bla.html
Is this possible using a regex? If so, how?
My current solution is to split the string into an array, and join its last two members again, but I'm sure that there is a better solution than this.
For example:
> '/foo/bar/baz/hello/world/bla.html'.replace(/.*(\/.*\/.*)/, "$1")
/world/bla.html
You can also do
str.split(/(?=\/)/g).slice(-2).join('')
> '/foo/bar/baz/hello/world/bla.html'.match(/(?:\/[^/]+){2}$/)[0]
"/world/bla.html"
Without regular expression:
> var s = '/foo/bar/baz/hello/world/bla.html';
> s.substr(s.lastIndexOf('/', s.lastIndexOf('/')-1))
"/world/bla.html"
I think this will work:
var str = "/foo/bar/baz/hello/world/bla.html";
alert( str.replace( /^.*?(\/[^/]*(?:\/[^/]*)?)$/, "$1") );
This will allow for there being possibly only one last part (like, "foo/bar").
You can use /(\/[^\/]*){2}$/ which selects a slash and some content twice followed by the end of the string.
See this regexplained.

Javascript regex match for string "game_1"

I just can't get this thing to work in javascript. So, I have a text "game_1" without the quotes and now i want to get that number out of it and I tried this:
var idText = "game_1";
re = /game_(.*?)/;
found = idText.match(re);
var ajdi = found[1];
alert( ajdi );
But it doesn't work - please point out where am I going wrong.
If you're only matching a number, you may want to try
/game_([0-9]+)/
as your regular expression. That will match at least one number, which seems to be what you need. You entered a regexp that allows for 0 characters (*) and let it select the shortest possible result (?), which may be a problem (and match you 0 characters), depending on the regex engine.
If this is the complete text, then there is no need for regular expressions:
var id = +str.split('_')[1];
or
var id = +str.replace('game_', '');
(unary + is to convert the string to a number)
If you insist on regular expression, you have to anchor the expression:
/^game_(.*?)$/
or make the * greedy by omitting the ?:
/game_(.*)/
Better is to make the expression more restrictive as #Naltharial suggested.
Simple string manipulation:
var idText = "game_1",
adji = parseInt(idText.substring(5), 10);
* means zero or more occurrences. It seems that combining it with a greediness controller ? results in zero match.
You could replace * with + (which means one or more occurrences), but as #Felix Kling notes, it would only match one digit.
Better to ditch the ? completely.
http://jsfiddle.net/G8Qt7/2/
Try "game_1".replace(/^(game_)/, '')
this will return the number
You can simply use this re /\d+/ to get any number inside your string

Better RegEx to extract GoogleVideo ID from URL

HI!
I use this the following regex with JS to extract this id 6321890784249785097 from that url
http://video.google.com/googleplayer.swf?docId=6321890784249785097
url.replace(/^[^\$]+.(.{19}).*/,"$1");
But I only cut the last 19 chars from the tail. How can I make to more bullet-proof? Maybe with an explanation so that I learn something?
This should work a bit better:
/^.*docId=(\d+)$/
This matches all characters up to the 'docId=', then gives you all digits after that up to the end of the url.
video[.]google[.]com/googleplayer[.]swf[?]docId=(\d+)
The ID will be captured in reference #1. If you just want to match 19 digits you can chance it to this:
video[.]google[.]com/googleplayer[.]swf[?]docId=(\d{19})
url.replace(/.*docId=(\d{19}).*/i,"$1");
this cuts 19 digits that follow docId=.
Here is the function I use in our app to read url parameters. So far it didn't let me down ;)
urlParam:function(name, w){
w = w || window;
var rx = new RegExp('[\&|\?]'+name+'=([^\&\#]+)'),
val = w.location.href.match(rx);
return !val ? '':val[1];
}
For the explanation of the regexp:
[\&|\?] take either the start of the query string '?' or the separation between parameters '&'
'name' will be the name of the parameter 'docId' in your case
([^\&#]+) take any characters that are not & and #. The hash key is often used in one page apps. And the parenthesis keep the reference of the content.
val will be an array or null/undefined and val[1] the value you are looking for

Categories

Resources