How to correctly extract part of a string js? - javascript

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'));

Related

GTM - Truncated DataLayer Variable into Custom Javascript Variable

I currently have a dlv variable to store "First Name" (gtm.element.2.value) which is working correctly.
I also a dlv to store "D.O.B." which is also working correctly - gtm.element.5.value (this is formatted MM/DD/YYYY).
However, I'd like to only show the first initial in the First Name dlv and the Year in the DOB dlv. I'm thinking of utilizing a Custom JS variable but am open to ideas if there is an easier route.
Can anyone help provide what that Custom JS variable would look like? I've been searching for some examples but not having luck with this specific example.
Appreciate the help in advance!
To get the first initial (i.e. first character) of the First Name variable, you can indeed use a Custom JavaScript variable with this:
function() {
return {{first_name}}[0]; // Replace with the actual DLV reference
}
Similarly, to get just the year (YYYY) of the D.O.B., you can use a Custom JS variable:
function() {
return {{date_of_birth}}.split('/').pop(); // Replace with the actual DLV reference
}
Obviously you might want to add some checks to make sure the input is in a predictable format. For example, you might want to check that {{first_name}} is a string of non-zero length, and you might want to check that {{date_of_birth}} actually contains a date string with slash as the separator.

Extract value from location hash

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.

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]);

store return json value in input hidden field

I was wondering if it's possible to store the return json in a hidden input field. For example this is what my json return:
[{"id":"15aea3fa","firstname":"John","lastname":"Doe"}]
I would like to just store the id in a hidden field so I can reference it later to do something with it.
Example: I have something like this:
<input id="HiddenForId" type="hidden" value="" />
and would like jquery to return the value later to me like so:
var scheduletimeid = $('#HiddenForId').val();
Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...
Here I'll explain what I mean:
<input type="hidden" value="{"name":"John"}">
As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:
<input type="hidden" value="{" rubbish >
So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:
> encodeURIComponent(JSON.stringify({"name":"John"}))
> "%7B%22name%22%3A%22John%22%7D"
Now that value can be safely stored in an input hidden type like so:
<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">
or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:
<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>
Now to read the data back we can do something like:
> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
> console.log(data)
> Object {name: "John"}
You can use input.value = JSON.stringify(obj) to transform the object to a string.And when you need it back you can use obj = JSON.parse(input.value)
The JSON object is available on modern browsers or you can use the json2.js library from json.org
You can store it in a hidden field, OR store it in a javascript object (my preference) as the likely access will be via javascript.
NOTE: since you have an array, this would then be accessed as myvariable[0] for the first element (as you have it).
EDIT show example:
clip...
success: function(msg)
{
LoadProviders(msg);
},
...
var myvariable ="";
function LoadProviders(jdata)
{
myvariable = jdata;
};
alert(myvariable[0].id);// shows "15aea3fa" in the alert
EDIT: Created this page:http://jsfiddle.net/GNyQn/ to demonstrate the above. This example makes the assumption that you have already properly returned your named string values in the array and simply need to store it per OP question. In the example, I also put the values of the first array returned (per OP example) into a div as text.
I am not sure why this has been viewed as "complex" as I see no simpler way to handle these strings in this array.
If you use the JSON Serializer, you can simply store your object in string format as such
myHiddenText.value = JSON.stringify( myObject );
You can then get the value back with
myObject = JSON.parse( myHiddenText.value );
However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.
It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).
Anyway, if that is an array wrapper, you'll want something like this:
$('#my-hidden-field').val(theObject[0].id);
You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,
$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;
This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.
just set the hidden field with javascript :
document.getElementById('elementId').value = 'whatever';
or do I miss something?
base64 solution
// encode
theInput.value = btoa(JSON.stringify({ test: true }));
// decode
let decoded = JSON.parse(atob(theInput.value));
Why base64?
The input field may be processed by a backend that runs in a different programming language than JavaScript. For instance, in PHP, rawurlencode implementation is slightly different from JavaScript encodeURIComponent. By encoding it in base64, you are sure that whatever other programming language runs on the backend, it will process it as expected.

Categories

Resources