Here's my little javascript, which will save utm params into people properties. Really useful for filtering, which user was acquired by a specific marketing channel.
Just put this code after you initialize mixpanel:
<script type="text/javascript">
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
var params = getQueryStrings();
for(var i in params) {
var match = /utm_[a-z]+/
if (match.test(i)) {
var value = params[i];
mixpanel.people.set_once(i, value);
}
}
</script>
Related
I'm hoping this is a quick answer for someone. I have built a form that is passing a few query params to the end of the URL and I'm using Jquery to get the param values based on the param names. My JQuery code seems to be case-sensitive which is causing some issues. For example, my param name is 'Blah' and my Jquery code is looking for 'blah', and it it won't work. Is there an easy way to update this code to be case-insensitive so that I don't have to manually account for all possible cases (e.g. blah, Blah, BLAH, blAh, blaH, etc.)?
Sample Jquery Code:
(function ($) {
$.getQuery = function (query) {
query = query.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var expr = "[\\?&]" + query + "=([^&#]*)";
var regex = new RegExp(expr);
var results = regex.exec(window.location.href);
if (results !== null) {
return results[1];
return decodeURIComponent(results[1].replace(/\+/g, " "));
} else {
return false;
}
};
})(jQuery);
var lang = $.getQuery('blah');
I also have similar code that I'm using in JavaScript that is case-sensitive too. Is there an easy way to change this code to be case-insensitive as well?
var dURL = document.URL;
function getParams() { //Get Name and (=) Values out of URL string after each &
var idx = dURL.indexOf('?');
var pnd = dURL.indexOf('#');
var fparams = new Array();
if (idx > -1) {
if (pnd > idx) {
var pairs = dURL.substring(idx + 1, (pnd - idx)).split('&');
} else {
var pairs = dURL.substring(idx + 1, document.URL.length).split('&');
}
for (var i = 0; i < pairs.length; i++) {
nameVal = pairs[i].split('=');
fparams[nameVal[0]] = nameVal[1];
}
}
return fparams;
}
var params = getParams();
if (params["blah"] != window.undefined) {
lang = unescape(params["blah"]);
} else {
blah= '';
}
Any information that can be provided would be greatly appreciated!
Using js toLower should work
(function ($) {
$.getQuery = function (query) {
query = query.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var expr = "[\\?&]" + query + "=([^&#]*)";
var regex = new RegExp(expr);
var results = regex.exec(window.location.href.toLower());
if (results !== null) {
return results[1];
return decodeURIComponent(results[1].replace(/\+/g, " "));
} else {
return false;
}
};
})(jQuery);
I have used the following code so I can add multiple parameter to a url
<script>
function setParam(name, value) {
var l = window.location;
/* build params */
var params = {};
var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
var s = l.search;
for(var r = x.exec(s); r; r = x.exec(s))
{
r[1] = decodeURIComponent(r[1]);
if (!r[2]) r[2] = '%%';
params[r[1]] = r[2];
}
/* set param */
params[name] = encodeURIComponent(value);
/* build search */
var search = [];
for(var i in params)
{
var p = encodeURIComponent(i);
var v = params[i];
if (v != '%%') p += '=' + v;
search.push(p);
}
search = search.join('&');
/* execute search */
l.search = search;
}
</script>
add priceMin=300
add priceMin=600
add MaxDistance=300
This is taken from question: How to add a parameter to the URL?
However what additional script would need to be added so if you clicked on the same hyperlink again it would remove the parameter in the url? In this case being '?priceMin=300'
Javascript already have URL objects.you can append the param if you want something
like this.
const newUrl = new URL(window.location.href);
function setParam(name, value, option = 'add') {
var paramexist = newUrl.searchParams.has(name);
if (option == 'remove') {
newUrl.searchParams.delete(name);
return newUrl;
}
(!paramexist) ? newUrl.searchParams.append(name, value) : newUrl.searchParams.set(name, value);
return newUrl;
}
console.log(setParam('priceMin', 300));
console.log(setParam('priceMin', 300,'remove'))
Hero Qu's answer will reset the entire list of parameters if you have multiple parameters.
The way to do this is to check if that specific parameter exists then delete it, otherwise add it.
I modified your code below to account for multiple parameter.
<script>
function setParam(name, value) {
var l = window.location;
/* build params */
var params = {};
var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
var s = l.search;
for (var r = x.exec(s); r; r = x.exec(s)) {
r[1] = decodeURIComponent(r[1]);
if (!r[2]) r[2] = '%%';
params[r[1]] = r[2];
}
/** Check to see if the param exist already
Delete if it exist, set it, if it doesn't
**/
if (params[name] && value == params[name]) {
delete params[name];
} else if (params[name] && value != params[name]) {
delete params[name];
params[name] = encodeURIComponent(value);
} else {
params[name] = encodeURIComponent(value);
}
/* set param */
/* build search */
var search = [];
for (var i in params) {
var p = encodeURIComponent(i);
var v = params[i];
if (v != '%%') p += '=' + v;
search.push(p);
}
search = search.join('&');
/* execute search */``
l.search = search;
}
</script>
add priceMin=200
<br />
add priceMin=300
<br />
add priceMax=400
you can try with adding an if block that would clear the search if it is already there OR allow to add param if the search is empty:
function setParam(name, value) {
var l = window.location;
if (l.search) {
l.search = ''
return
}
...
}
My question is about full power solution for parsing ANY complex URI parameters using just normal browser's Javascript. Like it do PHP, for simple code compatibility between JS and PHP sources.
But the first, let us see some particular known decisions:
1.
There is popular question and answers on StackOverflow, see How can I get query string values in JavaScript?
You can find there quite simple solutions for common SIMPLE cases. For example, like handling this scalar parameters like this one:
https://example.com/?name=Jonathan&age=18
It has no answers for handling complex query params. (As far as I could see for answers with source codes and author comments)
2.
Also you may use an URL object in modern browsers, see https://developer.mozilla.org/en-US/docs/Web/API/URL, or exactly https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams
It is enought powerful and you don't need to write or load any code for parsing URI parameters - just use
var params = (new URL(document.location)).searchParams;
var name = params.get("name"); // is the string "Jonathan"
var age = parseInt(params.get("age")); // is the number 18
This approach has such disadvantage that URL is available only in most of modern browsers, - other browsers or outdated versions of browsers will fail.
So, what I need. I need parsing any complex URI params, like
https://example.com/?a=edit&u[name]=Jonathan&u[age]=18&area[]=1&area[]=20&u[own][]=car&u[own][]=bike&u[funname]=O%27Neel%20mc%20Fly&empty=&nulparam&the%20message=Hello%20World
to
{
'a': 'edit',
'u': {
'name': 'Jonathan',
'age': '18',
'own': ['car', 'bike'],
'funname': 'O\'Neel mc Fly'
},
'area': [1, 20],
'empty': '',
'nulparam': null,
'the message': 'Hello World'
}
Preferrable answer is just plain readable javascript source. Simple and small wide-used library can be accepted too, but this question is not about them.
`
PS:
To start I just publish my own current solution for parsing URI params and vice versa for making URI from params. Any comments for it are welcome.
Hope this helps to save time for lot of coders later.
My solution
Usage:
var params = getQueryParams(location.search);
var params = getQueryParams();
var params = {...};
var path = '...';
var url = path;
var urlSearch = getQueryString(params);
if (urlSearch) {
url += '?' + urlSearch;
}
history.replaceState({"autoUrl": url}, "autoreplace", url);
Code:
function getQueryParams(qs) {
if (typeof qs === 'undefined') {
qs = location.search;
}
qs = qs.replace(/\+/g, ' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
var name = decodeURIComponent(tokens[1]);
var value = decodeURIComponent(tokens[2]);
if (value.length == 0) {
continue;
}
if (name.substr(-2) == '[]') {
name = name.substr(0, name.length - 2);
if (typeof params[name] === 'undefined') {
params[name] = [];
}
if (value === '') {
continue;
}
params[name].push(value);
continue;
}
if (name.substr(-1) == ']') {
var nameParts = name.split('[');
name = nameParts[0];
for (var i = 1; i < nameParts.length; i++) {
nameParts[i] = nameParts[i].substr(0, nameParts[i].length - 1);
}
var ptr = params;
for (var i = 0; i < nameParts.length - 1; i++) {
name = nameParts[i];
if (typeof ptr[name] === 'undefined') {
ptr[name] = {};
}
ptr = ptr[name];
}
name = nameParts[nameParts.length - 1];
ptr[name] = value;
continue;
}
params[name] = value;
}
return params;
}
function getQueryString(params) {
var paramsStringParts = [];
for (var name in params) {
if (params[name] instanceof Array) {
paramsStringParts.push( name + '[]=' + params[name].join('&' + name + '[]=') );
} else if (typeof params[name] === 'object') {
var makeFlattern = function(obj){
var result = [];
if (obj instanceof Array) {
for (var i = 0; i < obj.length; i++) {
result.push('[]=' + obj[i]);
}
return result;
}
for (var i in obj) {
if (typeof obj[i] === 'object') {
var subResult = makeFlattern(obj[i]);
for (var j = 0; j < subResult.length; j++) {
result.push('[' + i + ']' + subResult[j]);
}
continue;
}
result.push('[' + i + ']=' + obj[i]);
}
return result;
};
paramsStringParts.push( name + makeFlattern(params[name]).join('&' + name) );
} else {
paramsStringParts.push( name + '=' + params[name] );
}
}
return paramsStringParts.join('&');
}
A bit late, but just struggled over the same problem, solution was very simple:
use encodeURIComponent(...) for the stringified complex objects, the result can then be used as normal queryString-Part.
In the result-side the query-string-parameters have to be un-stringified.
Example:
var complex_param_obj = {
value1: 'Wert1',
value2:4711
};
console.log(restored_param_obj);
var complex_param_str = encodeURIComponent(JSON.stringify(complex_param_obj));
console.log(complex_param_str);
var complex_param_url = 'http://test_page.html?complex_param=' + complex_param_str;
//on the result-side you would use something to extract the complex_param-attribute from the URL
//in this test-case:
var restored_param_obj = decodeURIComponent(complex_param_str);
console.log(restored_param_obj);
I need to retrieve variables from an URL.
I use this found function:
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
The output is:
{"idPagamenti":["26","27"],"idCliente":["9"]}
But idCliente is always NOT an array, so i'd like to retrieve:
{"idPagamenti":["26","27"],"idCliente": 9 }
This is the fiddle example
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var stringa = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
$(document).ready(function(){
alert("testing");
console.log(me);
$(".a").html(JSON.stringify(me));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
</div>
Someone can help me to modify code?
I think your facing a real paradigm problem. Why idCliente wouldn't be an array but idPagamenti would be. You should have all array or none but not both. getParams() function can make this choice for you and you should probably change the way you are working with this.
Anyway, here is a getParams() function that replace any single-valued array to a value. Note that if you have only one idPagamenti in your URI, you will also have a single value for idPagamenti instead of an array.
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
Object.keys(obj).forEach(key => {
if (obj[key].length === 1) {
obj[key] = obj[key][0];
}
})
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
If you know that you will always get ids as parameters, you can also add a parseInt() for each parameter by replacing var value = spl[1]; with var value = parseInt(spl[1], 10);
I'm using jQuery 1.12. I want to replace a query string parameter in my window's URL query string, or add the parameter if doesn't exist. I tried the below:
new_url = window.location.href.replace( /[\?#].*|$/, "?order_by=" + data_val )
window.location.href = new_url
but what I'm discovering is that this wipes out all previous parameters in the query string, which I don't want. If the query string is:
?a=1&b=2
I would want the new query string to be:
?a=2&b=2&order_by=data
and if the query string was:
?a=2&b=3&order_by=old_data
it would become:
?a=2&b=3&order_by=data
You could use a jQuery plugin to do the all the heavy lifting for you. It will parse the query string, and also reconstruct the updated query string for you. Much less code to deal with.
Plugin Download Page
Github Repo
// URL: ?a=2&b=3&order_by=old_data
var order_by = $.query.get('order_by');
//=> old_data
// Conditionally modify parameter value
if (order_by) {
order_by = “data”;
}
// Inject modified parameter back into query string
var newUrl = $.query.set(“order_by”, order_by).toString();
//=> ?a=2&b=3&order_by=data
For those using Node.js, there is a package for this available in NPM.
NPM Package
Github Repo
var queryString = require('query-string');
var parsed = queryString.parse('?a=2&b=3&order_by=old_data'); // location.search
// Conditionally modify parameter value
if (parsed.order_by) {
parsed.order_by = 'data';
}
// Inject modified parameter back into query string
const newQueryString = queryString.stringify(parsed);
//=> a=2&b=3&order_by=data
A good solution ought to handle all of the following:
A URL that already has an order_by query parameter, optionally with whitespace before the equals sign. This can be further divided into cases where the order_by appears at the start, middle or end of the query string.
A URL that doesn't already have and order_by query parameter but does already have a question mark to delimit the query string.
A URL that doesn't already have and order_by query parameter and doesn't already have a question mark to delimit the query string.
The following will handle the cases above:
if (/[?&]order_by\s*=/.test(oldUrl)) {
newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
} else if (/\?/.test(oldUrl)) {
newUrl = oldUrl + "&order_by=" + data_val;
} else {
newUrl = oldUrl + "?order_by=" + data_val;
}
as demonstrated below:
getNewUrl("?a=1&b=2");
getNewUrl("?a=2&b=3&order_by=old_data");
getNewUrl("?a=2&b=3&order_by = old_data&c=4");
getNewUrl("?order_by=old_data&a=2&b=3");
getNewUrl("http://www.stackoverflow.com");
function getNewUrl(oldUrl) {
var data_val = "new_data";
var newUrl;
if (/[?&]order_by\s*=/.test(oldUrl)) {
newUrl = oldUrl.replace(/(?:([?&])order_by\s*=[^?&]*)/, "$1order_by=" + data_val);
} else if (/\?/.test(oldUrl)) {
newUrl = oldUrl + "&order_by=" + data_val;
} else {
newUrl = oldUrl + "?order_by=" + data_val;
}
console.log(oldUrl + "\n...becomes...\n" + newUrl);
}
something like this?
let new_url = "";
if (window.location.search && window.location.search.indexOf('order_by=') != -1) {
new_url = window.location.search.replace( /order_by=\w*\d*/, "order_by=" + data_val);
} else if (window.location.search) {
new_url = window.location.search + "&order_by=" + data_val;
} else {
new_url = window.location.search + "?order_by=" + data_val;
}
window.location.href = new_url;
function addOrReplaceOrderBy(newData) {
var stringToAdd = "order_by=" + newData;
if (window.location.search == "")
return window.location.href + stringToAdd;
if (window.location.search.indexOf('order_by=') == -1)
return window.location.href + stringToAdd;
var newSearchString = "";
var searchParams = window.location.search.substring(1).split("&");
for (var i = 0; i < searchParams.length; i++) {
if (searchParams[i].indexOf('order_by=') > -1) {
searchParams[i] = "order_by=" + newData;
break;
}
}
return window.location.href.split("?")[0] + "?" + searchParams.join("&");
}
window.location.href = addOrReplaceOrderBy("new_order_by");
A little long but I think it works as intended.
You can remove parameter from query string using URLSearchParams https://developer.mozilla.org/ru/docs/Web/API/URLSearchParams?param11=val
It is not yet supported by IE and Safari, but you can use it by adding polyfill https://github.com/jerrybendy/url-search-params-polyfill
And for accessing or modifying query part of the URI you should use "search" property of the window.location.
Working code example:
var a = document.createElement("a")
a.href = "http://localhost.com?param1=val¶m2=val2¶m3=val3#myHashCode";
var queryParams = new URLSearchParams(a.search)
queryParams.delete("param2")
a.search = queryParams.toString();
console.log(a.href);
Try this:
For reading parameters:
const data = ['example.com?var1=value1&var2=value2&var3=value3', 'example.com?a=2&b=2&order_by=data']
const getParameters = url => {
const parameters = url.split('?')[1],
regex = /(\w+)=(\w+)/g,
obj = {}
let temp
while (temp = regex.exec(parameters)){
obj[temp[1]] = decodeURIComponent(temp[2])
}
return obj
}
for(let url of data){
console.log(getParameters(url))
}
For placing only this parameters:
const data = ['example.com?zzz=asd']
const parameters = {a:1, b:2, add: "abs"}
const setParameters = (url, parameters) => {
const keys = Object.keys(parameters)
let temp = url.split('?')[0] += '?'
for (let i = 0; i < keys.length; i++) {
temp += `${keys[i]}=${parameters[keys[i]]}${i == keys.length - 1 ? '' : '&'}`
}
return temp
}
for (let url of data){
console.log(setParameters(url, parameters))
}
And finaly for inserting (or replace while exists)
const data = ['example.com?a=123&b=3&sum=126']
const parameters = {order_by: 'abc', a: 11}
const insertParameters = (url, parameters) => {
const keys = Object.keys(parameters)
let result = url
for (let i = 0; i < keys.length; i++){
if (result.indexOf(keys[i]) === -1) {
result += `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`
} else {
let regex = new RegExp(`${keys[i]}=(\\w+)`)
result = result.replace(regex, `&${keys[i]}=${encodeURIComponent(parameters[keys[i]])}`)
}
}
return result
}
for (let url of data){
console.log(insertParameters(url, parameters))
}
Hope this works for you ;)
After using function just replace window.location.href
This small function could help.
function changeSearchQueryParameter(oldParameter,newParameter,newValue) {
var parameters = location.search.replace("?", "").split("&").filter(function(el){ return el !== "" });
var out = "";
var count = 0;
if(oldParameter.length>0) {
if(newParameter.length>0 && (newValue.length>0 || newValue>=0)){
out += "?";
var params = [];
parameters.forEach(function(v){
var vA = v.split("=");
if(vA[0]==oldParameter) {
vA[0]=newParameter;
if((newValue.length>0 || newValue>=0)) {
vA[1] = newValue;
}
} else {
count++;
}
params.push(vA.join("="));
});
if(count==parameters.length) {
params.push([newParameter,newValue].join("="));
}
params = params.filter(function(el){ return el !== "" });
if(params.length>1) {
out += params.join("&");
}
if(params.length==1) {
out += params[0];
}
}
} else {
if((newParameter.length>0) && (newValue.length>0 || newValue>=0)){
if(location.href.indexOf("?")!==-1) {
var out = "&"+newParameter+"="+newValue;
} else {
var out = "?"+newParameter+"="+newValue;
}
}
}
return location.href+out;
}
// if old query parameter is declared but does not exist in url then new parameter and value is simply added if it exists it will be replaced
console.log(changeSearchQueryParameter("ib","idx",5));
// add new parameter and value in url
console.log(changeSearchQueryParameter("","idy",5));
// if no new or old parameter are present url does not change
console.log(changeSearchQueryParameter("","",5));
console.log(changeSearchQueryParameter("","",""));
Maybe you could try tweaking the regular expression to retrieve only the values you're looking for, then add or update them in a helper function, something like this:
function paramUpdate(param) {
var url = window.location.href,
regExp = new RegExp(param.key + '=([a-z0-9\-\_]+)(?:&)?'),
existsMatch = url.match(regExp);
if (!existsMatch) {
return url + '&' + param.key + '=' + param.value
}
var paramToUpdate = existsMatch[0],
valueToReplace = existsMatch[1],
updatedParam = paramToUpdate.replace(valueToReplace, param.value);
return url.replace(paramToUpdate, updatedParam);
}
var new_url = paramUpdate({
key: 'order_by',
value: 'id'
});
window.location.href = new_url;
Hope it works well for your needs!
To use Regex pattern, I prefer this one:
var oldUrl = "http://stackoverflow.com/";
var data_val = "newORDER" ;
var r = /^(.+order_by=).+?(&|$)(.*)$/i ;
var newUrl = "";
var matches = oldUrl.match(r) ;
if(matches===null){
newUrl = oldUrl + ((oldUrl.indexOf("?")>-1)?"&":"?") + "order_by=" + data_val ;
}else{
newUrl = matches[1]+data_val+matches[2]+matches[3] ;
}
conole.log(newUrl);
If no order_by exist, matches is null and order_by=.. should come after ? or & (if other parameters exist, new one needs &).
If order_by exist, matches has 3 items, see here
Based on AVAVT´s answer I improved it so it takes any key, and I also fixed the missing "?" if there was no querystring
function addOrReplace(key, value) {
var stringToAdd = key+"=" + value;
if (window.location.search == "")
return window.location.href + '?'+stringToAdd;
if (window.location.search.indexOf(key+'=') == -1)
return window.location.href + stringToAdd;
var newSearchString = "";
var searchParams = window.location.search.substring(1).split("&");
for (var i = 0; i < searchParams.length; i++) {
if (searchParams[i].indexOf(key+'=') > -1) {
searchParams[i] = key+"=" + value;
break;
}
}
return window.location.href.split("?")[0] + "?" + searchParams.join("&");
}
usuage:
window.location.href = addOrReplace('order_by', 'date_created');
if you would not want to reload the page you can use pushState Api
if (history.pushState) {
var newurl = addOrReplace('order_by', 'date_created');
window.history.pushState({path:newurl},'',newurl);
}
function myFunction() {
var str = "https://www.citicards.com/cards/credit/application/flow.action?app=UNSOL&HKOP=828cca70910b4fe25e118bd0b59b89c3c7c560df877909495d8252d20026cf8d&cmp=afa|acquire|2003|comparecards&ranMID=44660&ranEAID=2759285&ProspectID=516511657A844EF3A6F0C2B1E85FEFB0&ID=3000";
var res = str.split("&");
var myKey;
if (!str.includes("ranSiteID")) {
console.log("key not found ");
res.push('ranSiteID=samplearsdyfguh.090-nuvbknlmc0.gvyhbjknl')
console.log(res.join("&"));
} else {
res.map(function(key) {
console.log("my keys", key);
if (key.includes("ranSiteID")) {
console.log("my required-->key", key);
mykey = key.split("=");
console.log(mykey);
}
})
}
document.getElementById("demo").innerHTML = res;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>