Extract value from location hash - javascript

In the front-end Javascript code, I need to extract a value from the location hash parameter.
For example, the url looks like:
https://mywebsite.com/certainpage#comment-12345
Here, I want to extract the value 12345 which indicates the id of comment. Currently, I am using the following code to do it:
const match = window.location.hash.match(/-([0-9]*)/) || [];
if (!match[1]) return;
// Use match[1]
If there is any optimized and clean way to handle this, please let me know.

If it's always #comment-NUM, then you don't even need to go for RegEx.
const match = window.location.hash.split("-") || [];
Then the same checks will apply. Use match[1] going forward. The reason is, String.split is better in performance than String.match. Also, it looks lot cleaner too.

Related

How to correctly extract part of a string js?

I have a URL and I need to isolate a certain value from it, and to be more precise, the value after numberType=.
There may or may not be an ampersand after this value. How can I implement this with a generic function?
Examples
http://localhost:8080/type/3259/?filters=901&numberType=77
http://localhost:8080/type/3259/?filters=901&numberType=77&somethingElse=string
Let the URL class do the heavy lifting for you:
const input = 'http://localhost:8080/type/3259/?filters=901&numberType=77';
const parsed = new URL(input);
console.log(parsed.searchParams.get('numberType'));

How to get value from string with lodash?

Suppose I have a url that looks like this:
http://mysite/super/id/800
The 'super/id' part in the URL is fixed.I am trying to create a compact statement to return the 800 value with lodash. What could be a solution for this. I know how to split it up into an array and then get it from there but just looking for a more elegant solution?
Although it's not lodash I would argue that given the 800 portion of the string is certain to be the final part, the following is cleanest.
string.split('/').pop();
It's best (in my opinion) to avoid using frameworks and libraries unless there is a deficit in the language requiring you to do so.
If you want to avoid creating an array, you could try using String#slice and String#lastIndexOf:
var string = 'http://mysite/super/id/800'
console.log(
string.slice(string.lastIndexOf('/') + 1) //=> '800'
)
Try Regular Expressions
Your url seems to be a good candidate.
var url = "http://mysite/super/id/800";
var pattern = /\d+$/;
var match = pattern.exec(url);
// ["800"], it will be null if there was no match

is my anti xss function safe?

I have some javascript functions on my website, but I don't know if it is safe to use them.
here is my code :
// works like PHP's $_GET
function get(name){
name=name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
regexS="[\\?&]"+name+"=([^&#]*)";
regex=new RegExp(regexS);
results=regex.exec(window.location.href);
if(results==null)
return '';
return results[1];
}
// and here is my anti xss filter
var param = unescape(decodeURI(get("q")));
param = param.replace(/<(.*?)>/gi, "");
someElement.innerHTML = param;
Is it possible to bypass this filters?
Do not try and find XSSes on the way into your application. Your program may transform the data internally in such a way that any filter you create is likely to be circumventable.
Instead, apply proper HTML encoding of data on the way out of your application. That way you avoid the vulnerabilities.
No, but if you simulate multiline mode in your second last line like this:
param = param.replace(/<([\s\S]*?)>/gi, "");
your example code would be safe as it is. The biggest flaw in your example code is using innerHTML when you do not want to add HTML at all. So instead of using innerHTML and trying to filter out HTML you should use createTextNode and you will not have to worry about XSS anymore. So keep your get function if you like it, and use the parameter values like this (adapted from MDN):
var param = unescape(decodeURI(get("q")));
var text = document.createTextNode(param);
document.getElementById(someElement).appendChild(newtext);
If you use jQuery, you can use .text() function, which itself uses createTextNode.

How to get an Id out of a Url client side?

If I have a URl like "/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d" what would be the best way to get the ID "2c02ds92-25cb-43e1-9bba-3bd5604a0a3d" out of the URL client side?
I need to be able to build a $.getJSON request with the ID and I'm looking for the cleanest way to do it using JavaScript, jQuery, etc. Thanks
$.getJSON('/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d')...
Use regular expressions and extract the appropriate part (which seems to be UUID) from the URL.
The alternative is to just split the string by / and get last element.
EDIT: The example on how to retrieve UUID from the URI:
var url = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d';
var pattern = /[\da-f]{8}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{12}/;
var match = url.match(pattern)[0];
url.match(pattern) returns array of matches, so assuming there is at least one, and only one match, you should pick it (using [0], as in the example).
Proof: http://jsfiddle.net/p6zud/2/
EDIT 2: Shortened the pattern used for matching (see revision history for comparison).
If the id is always going to be the last section of the URI, you could do something like
var url_array = document.location.split('/');
var id = url_array[url_array.length - 1];
using split, convert the url to an array of parameters. Then last array item in your case would be your ID.
there are very sophisticated URL parsers out there for javascript, perhaps you should look around on google for one that suits your needs.
The simpliest:
var id = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d'.split('/User/')[1];
Gives you 2c021192-25cb-43e1-9bba-3bd5604a0a3d;
Try this
alert("/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d".split('/').slice(-1)[0]);

What would be the regex to get the view code from youtube urls?

I just need to get the view code from youtube urls. The api is returning back strings that look like this:
http:\/\/www.youtube.com\/watch?v=XODUrTtvZks&feature=youtube_gdata_player
I need to get this part:
XODUrTtvZks
from the above, keep in mind that sometimes there may be additional parameters after the v=something like:
&feature=youtube_gdata_player
and sometimes there may not be. Can someone please provide the regex that would work in this situation and an example of how to use it using javascript?
You can use /v=([^&]+)/ and get the match at offset 1.
This snippet only matches on URL's from youtube.com:
var url = 'http://www.youtube.com/watch?v=XODUrTtvZks&feature=youtube_gdata_player';
var matches = url.match(/^http[s]?:\/\/www.youtube.com\/watch\?\s*v=([^&]+)/i);
if (matches) {
var videoID = matches[1];
// do stuff
}
You can use an online tool called RegExr to get your regular expression ,[http://gskinner.com/RegExr/].
Regards
Rahul
This snippet is from Google’s own parser at closure:
function getIdFromUrl(url) {
return /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i.exec(url)[2];
}
You can see it here:
http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/ui/media/youtube.js?r=1221#246

Categories

Resources