Monday, May 27, 2019

string - Extract specific data from JavaScript .getAttribute()

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.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...