How can I search window.location.search for specific text? - javascript

I have the following code and I want it to show the div only when the part after the "?" includes "gclid=". Note the url could look like xxxxxx.com/?gclid=kljl3j4lk3j4l23
I am not quite sure how to incorporate a partial string search so it only looks for "?gclid"
<script type="text/javascript">
$(function(){
if (window.location.search == "?gclid") {
$('#new').show();
} else {
$('#new').hide();
}
});
</script>
I am a bit new to this so pardon my ignorance

You could use indexOf()
if(window.location.search.indexOf("gclid=") > -1)

if (window.location.search.match(/[?&]gclid=/))

You can do this either with a Regular Expression or substring and text parsing.
var stringPart = window.location.search.substr(0, 6);
if (stringPart == "?gclid") { ...
or
var re = new RegExp(/^\?gclid/);
if (window.location.search.match(re)) { ...
Both of those should get you there.

You can use javaScript split to do that
Suppose you have a url like
http://www.website.com/profile?var1=abc&var2=def&var3=ghi
//the url
var path = "http://www.website.com/profile?var1=abc&var2=def&var3=ghi";
//get all url parameters
var parameters = path.split("?")[1];
// get the parameters
var para1 = parameters.split("&")[0];
var para2 = parameters.split("&")[1];
var para3 = parameters.split("&")[2];
// get the parameter value
var para1var = para1.split("=")[1];
var para2var = para2.split("=")[1];
var para3var = para3.split("=")[1];

Extract each parameter one by one, working code:
http://localhost:10/mapserver1/viewer/?config=viewer_simple1&url=https://maps2.dcgis.dc.gov/dcgis/rest/services/Zoning/MapServer&zoom=17&lat=38.917292&long=-77.036420
You could do:
var ___zoom;
var ___lat;
var ___long;
var ___basemap;
var ___type;
var ___url;
var ___title;
var ___opacity;
/*
* if (value) {
*
* }
*
* will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
false
0
*
*
*
*/
if ( location.search.match(/zoom=([^&]*)/i) )
{
___zoom = location.search.match(/zoom=([^&]*)/i)[1];
}
if ( location.search.match(/lat=([^&]*)/i) )
{
___lat = location.search.match(/lat=([^&]*)/i)[1];
}
if (location.search.match(/long=([^&]*)/i))
{
___long = location.search.match(/long=([^&]*)/i)[1];
}
if (location.search.match(/basemap=([^&]*)/i))
{
___basemap = location.search.match(/basemap=([^&]*)/i)[1];
}
if (location.search.match(/type=([^&]*)/i))
{
___type = location.search.match(/type=([^&]*)/i)[1];
}
if (location.search.match(/url=([^&]*)/i))
{
___url = location.search.match(/url=([^&]*)/i)[1];
}
if (location.search.match(/title=([^&]*)/i))
{
___title = location.search.match(/title=([^&]*)/i)[1];
}
if (location.search.match(/opacity=([^&]*)/i))
{
___opacity = location.search.match(/opacity=([^&]*)/i)[1];
}
//console.log(location.search.match(/zoom=([^&]*)/i)[0]); // 'zoom=17'
//console.log(location.search.match(/zoom=([^&]*)/i)[1]); // '17'
console.log(___zoom);
console.log(___lat);
console.log(___long);
console.log(___basemap);
console.log(___type);
console.log(___url);
console.log(___title);
console.log(___opacity);

Related

stop converting xml tags to lowercase - jquery

I am working on Draw.io in which I have to convert json to XML, which I successfully did, But I am facing an issue in which all my xml tags goes to lowercase auto.
Lets Say, If I create tag with <mxCell></mxCell> it will convert into <mxcell></mxcell>.
BUT for draw.io , I need to keep the same format for XML. any way to do this ?
var apple = '<mxCell />';
var $div = $('<div>');
$div.append(apple);
$("#graphXMlDiv").text($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="graphXMlDiv"></div>
Working jsfiddle
Take a look to this:
let XMLTag = function(tagName) {
this.tagName = tagName;
this.children = [];
this.padding = '';
this.parent = null;
}
XMLTag.prototype.addPadding = function() {
this.padding = this.padding + '\t';
}
XMLTag.prototype.getPadding = function() {
var current = this;
let padding = '';
while (current !== null) {
padding += current.padding;
current = current.parent;
}
return padding;
}
XMLTag.prototype.setParent = function(parent) {
this.parent = parent;
}
XMLTag.prototype.append = function(child) {
child.addPadding();
child.setParent(this);
this.children.push(child);
}
XMLTag.prototype.toText = function() {
if (this.children.length === 0) {
return `${this.getPadding()}<${this.tagName}/>`;
} else {
let childrenText = this.children.map(c => c.toText()).join(`\n`);
return `${this.getPadding()}<${this.tagName}>\n${childrenText}\n${this.getPadding()}</${this.tagName}>`
}
}
var apple = new XMLTag('mxCell');
var anotherTag = new XMLTag('anotherTag');
var anotherTag1 = new XMLTag('anotherTag1');
apple.append(anotherTag);
anotherTag.append(anotherTag1);
console.log(apple.toText());
I'm not really sure what you going for so I am assuming two possible solutions.
You are looking to insert simple string instead of XML node
In that case, just do this:
var $div = $('<div/>');
$div.text('<mxCell><mxCell/>');
$("#graphXMlDiv").text($div.text());
//Then I would add the answer to this StackOverflow question
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="graphXMlDiv"></div>
Notice I don't use $div.html() to supply the data to $('#graph....') because what you've inserted inside $div is not proper HTML, and should not be treated as such.
In case you wanted to load an XML document and then add into $div the content of what the XML node myCell has, then you can do something like this.
var apple = '<mxCell>Data inside mxCell</mxCell>',
$div = $('<div/>')
$apple_xml = $($.parseXML(apple));
$apple_xml.find('mxCell').each(function() {
$div.html($(this).text());
});
$("#graphXMlDiv").text($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="graphXMlDiv"></div>

How to get multiple named querystring values in jQuery/Javascript?

I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]

Find id number in url using javascript

Currently I am scraping the end of an url using javascript like so:
var url = document.URL;
var sale = url.substring(url.lastIndexOf('/') + 1);
if(sale != "")
So if there is this /sales/1234 it would pick it up, trouble is it still works for something else like sales/anotherword/1234, is there an easy way to adjust this to only pick up the number after "/sales/"?
You could try using regular expressions:
var url = document.URL;
var sale = null;
var matches = url.match(/\/sales\/(\d+)/);
if(matches.length && matches[1]){
sale = matches[1];
}
You could do a bit more validating:
Make sure there is no / after the one after sales.
Make sure that the value you get is a number.
Something like this could work:
var url = document.URL;
var sale = url.substring(url.lastIndexOf('/sales/') + 1);
if(sale.indexOf('/') < 0 && !isNaN(sale)) {
//Handle the sale
}
else {
//sale either contains a / or is not a number
}
You could also do this :
var sale = parseInt(url.split('/sales/')[1], 10);
if (!isNaN(sale)) {
// do something
}
parseInt() returns NaN (Not A Number) in case of failure.
Here is a function :
function toSaleId(url) {
var id = parseInt(url.split('/sales/')[1], 10);
if (!isNaN(id)) return id;
}
Usage examples :
var sale = toSaleId('/sale/1234'); // 1234
var sale = toSaleId('/sale/1234/anotherworld'); // 1234
var sale = toSaleId('/sale/anotherworld/1234'); // undefined

How to get the parameter value from URL in Jquery?

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

Multiplying Variables Not Alerting

I have a script which calls variable values from input fields and multiplies them,
At the minute my function isnt executing, Im getting no alert neither, I think this is because of my if statement, can anybody see whats going wrong?
function Calculate() {
var ContentMinutes = document.getElementById ("ContentMinutes").value;
var ContentMinutesSelect = document.getElementById('ContentMinutesDD')
.options[document.getElementById('ContentMinutesDD').selectedIndex].value
if (ContentMinutesSelect == 0.0166)
{
var RenderingHours = 10;
var VideoHours = 5;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else if (ContentMinutesSelect == 0.0003)
{
var RenderingHours = 1540;
var VideoHours = 54;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else
{
var RenderingHours = 6410;
var VideoHours = 345;
var VideoSeconds = 124;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
var NoOfFrames = document.getElementById ("NoOfFrames").value;
//var EstimatedCoreHours = document.getElementById ("EstimatedCoreHours").value;
var ServiceLevel = document.getElementById('SerivceLevelDD')
.options[document.getElementById('SerivceLevelDD').selectedIndex].value;
var RenderHours = 1;
var CoresInTest = document.getElementById ("CoresInTest").value;
var EstimatedCoreHours = GetNumeric(NoOfFrames)
* GetNumeric(RenderingHours)
* GetNumeric(CoresInTest);
var EstimatedTotal = GetNumeric(ServiceLevel)
* GetNumeric(EstimatedCoreHours);
alert('Estimated Cost = '
+EstimatedTotal.toFixed(2)
+ 'Estimated Core Hours = '
+EstimatedCoreHours);
document.getElementById("EstimatedCoreHours").innerHTML =
EstimatedCoreHours.toFixed(2);
document.getElementById("EstimatedTotal").innerHTML =
EstimatedTotal.toFixed(2);
document.getElementById("EstimatedCoreHours").style.backgroundColor="yellow";
document.getElementById("EstimatedTotal").style.backgroundColor="yellow";
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
if (ContentMinutesSelect == 0.0166) i think when you do .value you will get string result.
So your comparision should be
if (ContentMinutesSelect == "0.0166")
Your code will display no alert if any line before it results in an error , like if there isn't an element with the id 'ContentMinutes' in your document . The best way to debug would be to use something like firebug , or you could always put in a bunch of alerts and figure out what goes wrong.

Categories

Resources