Monday 27 May 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...