Extract specific data from JavaScript .getAttribute() [duplicate] - javascript

This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?

There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.

You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions

Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed

Related

Same regex have different results in Java and JavaScript [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 3 years ago.
Same regex, different results;
Java
String regex = "Windows(?=95|98|NT|2000)";
String str = "Windows2000";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
System.out.println(m.matches()); // print false
JavaScript
var value = "Windows2000";
var reg = /Windows(?=95|98|NT|2000)/;
console.info(reg.test(value)); // print true
I can't understand why this is the case?
From the documentation for Java's Matcher#matches() method:
Attempts to match the entire region against the pattern.
The matcher API is trying to apply your pattern against the entire input. This fails, because the RHS portion is a zero width positive lookahead. So, it can match Windows, but the 2000 portion is not matched.
A better version of your Java code, to show that it isn't really "broken," would be this:
String regex = "Windows(?=95|98|NT|2000)";
String str = "Windows2000";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group()); // prints "Windows"
}
Now we see Windows being printed, which is the actual content which was matched.

Remove sub-string from URL containing only numbers [duplicate]

This question already has answers here:
How to remove numbers from a string?
(8 answers)
Closed 3 years ago.
I have a few URL's like these
https://{Domain}/rent/abcdef/2019/Canada
https:/{Domain}/buy/Supported/2019/Gill-Avenue
I want to remove '2019'or any part which contain only numbers from these Url's so that the Url's look as below
https://{Domain}/rent/abcdef/Canada
https:/{Domain}/buy/Supported/Gill-Avenue
How can i achieve this using javascript
You can try this;
let str = "https://test.com/rent/abcdef/2019/Canada";
str.replace(/\/\d+/g, '');
You should try something like that:
split on '/', filter with a /d regex and rejoin with '/'
I can't try right now sorry
window.location.href.split('/').filter(substr => !(/^\d+$/.match(substr))).join('/')
Try to do this for the first:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("f//", "f/");
And for the second:
var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("d//", "d/");
So this is if you want to replace just 1 digit. The first one of each of these works but adds a new / backslash to the whole link after the last letter before the / in the old version. To remove that, you do the second, which contains the last letter to not remove the :// too. The way is to find the last letter of each of these numbers before the backslash after using the first replace() function and replace them to remove the extra backslash.
This might work for easy things, like if you already know the URL, but for complicated things like a very big project, this is no easy way to do it. If you want "easy", then check other answers.
As said, you can also do this:
let str = "https://test.com/rent/abcdef/2019/Canada";
var withNoNum = str.replace(/\/\d+/g, '');
This is going to remove groups of numbers. So I added a new string withNoNum which is str's replacement with no numbers, which might be more good because if you are doing a website that allows you to send your own website and remove the numbers from it to get a new site.
This also might help you with this problem: removing numbers from string

Looking to trim a string using javascript / regex [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.
Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));
You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});

Spliting numbers out of a string contain characters and numbers [duplicate]

This question already has answers here:
Extract numbers from a string using javascript
(4 answers)
Closed 6 years ago.
I want to split the numbers out of a string and put them in an array using Regex.
For example, I have a string
23a43b3843c9293k234nm5g%>and using regex I need to get [23,43,3843,9293,234,5]
in an array
how can i achieve this?
Use String.prototype.match()
The match() method retrieves the matches when matching a string against a regular expression
Edit: As suggested by Tushar, Use Array.prototype.map and argument as Number to cast it as Number.
Try this:
var exp = /[0-9]+/g;
var input = "23a43b3843c9293k234nm5g%>";
var op = input.match(exp).map(Number);
console.log(op);
var text = "23a43b3843c9293k234nm5g%>";
var regex = /(\d+)/g;
alert(text.match(regex));
You get a match object with all of your numbers.
The script above correctly alerts 23,43,3843,9293,234,5.
see Fiddle http://jsfiddle.net/5WJ9v/307/

How to remove all characters after a certain index from a string [duplicate]

This question already has answers here:
Remove everything after a certain character
(10 answers)
Closed 9 years ago.
I am trying to remove all characters from a string after a specified index. I am sure there must be a simple function to do this, but I'm not sure what it is. I am basically looking for the javascript equivalent of c#'s string.Remove.
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.split("$")[0];
or
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.substring(0, myStr.indexOf("$") - 1);
Use substring
var x = 'get this test';
alert(x.substr(0,8)); //output: get this
You're looking for this.
string.substring(from, to)
from : Required. The index where to start the extraction. First character is at index 0
to : Optional. The index where to stop the extraction. If omitted, it extracts the rest of the string
See here: http://www.w3schools.com/jsref/jsref_substring.asp
I'd recommend using slice as you can use negative positions for the index. It's tidier code in general. For example:
var s = "messagehere";
var message = s.slice(0, -4);

Categories