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
Related
I am trying to get items according the first letter e.g if the items first letter is A I wand that item to appear in divA e.t.c
my code:
function onS() {
var lstString = "";
var Enum = listItems.getEnumerator();
while (Enum.moveNext())
{
var currentItem = Enum.get_current();
lstString += "<br/>" + currentItem.get_item("Title").substring(0,1);//here I check the first letter.
if (lstString = "A") {
$("#divA").html(); //here I want to get that item
}
}
}
If I understand your question, you can do it like this :
if( currentItem.get_item("Title").substring(0,1).toUpperCase() == 'A' )
// or
if( currentItem.get_item("Title")[0].toUpperCase() == 'A' )
Note : You need to use == instead = into an if condition.
var word = 'Aword';
var firstLetter = word[0];
var selector = '#div' + firstLetter;
var container = $(selector);
container.html(word);
Do you mean something like that?
Here is the working example: http://jsfiddle.net/9rky2nwh/
I am generating FINANCIAL ANALYSIS and i generate dynamic formula for chart of accounts.
Example
Cash -- Input able Field
Short Term Investments -- Input able Field
Liquid Assets -- Formula Field and i generate formula for this #1~Cº + #2~Cº
Notes Receivable -- Input able Field
Accounts Receivable -- Input able Field
Provision for Debts -- Input able Field
Net Accounts Receivable -- Formula Field and i generate formula for this #4~Cº + #5~Cº+#6~Cº
and so on...
i am calculating on text box focusout calculate_year.
function calculate_year(ThisObj) {
var obj;
//intiate vaiables
var year_formulaTxt = "",resultExp ="",lastPos ="",sequenceTypePosC="",sequenceTypePosP="",sequenceTypePosF="",COACode="",COAValue="",ratio_formulaTxt = "";
var ratio_formulaTxt = "",COACode_P="",COAValue_Pyear_formula = "",ratio_formula = "",year_formulaObj = "",ratio_formulaObj = "",year_formulaArr = "",ratio_formulaArr = "",FormulaResult="";
//match paterm for
var matchPattern = /[^\s()*/%+-/]+/g;
var tableId = $(ThisObj).closest('table').attr('id');
var CuurentDiv = $(ThisObj).closest('.program-column').index();
if (CuurentDiv < 2){ // to check if previous month added
CuurentDiv = CuurentDiv + 1 ;
}
var tableIdNext = $('.mCSB_container .program-column:eq('+CuurentDiv+') table').attr('id');
//get all textbox inside div
$('#'+tableId+' .financial_txt').each(function () {
//º
obj = $(this);
year_formulaObj = obj.find('input[type=text]');
ratio_formulaObj= obj.find('input[type=text]:eq(1)');
//calcualtion for only formula fields
if ($(year_formulaObj).attr('data-fieldtype') == "F") {
//get formula from custom field
year_formula = $(year_formulaObj).attr('year_formula');
if($.trim(year_formula) !=""){
//match formula with math's operator(Binary operator)
year_formulaArr = year_formula.match(matchPattern);
//break string # º : working for single experssion using loop
// ----------------------For Year ---------------------------
for( var i=0; i< year_formulaArr.length; i++ ){
//sub string from '#' to 'º'
lastPos = year_formulaArr[i].substring(1, year_formulaArr[i].length - 1);
//all sequence type
sequenceTypePosC = lastPos.indexOf("C");
sequenceTypePosP = lastPos.indexOf("P");
sequenceTypePosF = lastPos.indexOf("F");//
if(sequenceTypePosC >= 0){
//console.log(lastPos);
//getting value of COACode From Formula
COACode = lastPos.substring(0, sequenceTypePosC - 1);
//getting value of COACode From Text box id
COAValue = $.trim($('#'+tableId+' #txt_year_formula'+COACode).val()) == "" ? 0 : $.trim($('#'+tableId+' #txt_year_formula'+COACode).val());
$('#'+tableId+' #txt_year_formula'+COACode).val(COAValue);
//work for field value
var tempRes = year_formula.substring(year_formula.indexOf("#"), year_formula.indexOf("º")+1);
year_formula = year_formula.replace(tempRes,COAValue);
tempRes = year_formula;
//replace rest of # ,º with 0
tempRes = tempRes.replace(/\s*#[^º]+º\s*/g,parseFloat(0));
var result = parseFloat(mathEval(tempRes)).toFixed(3)|| 0;
$('#'+tableId+' #txt_year_formula'+$(this).attr('id')).val(mathEval(result) == "NaN" ?"0":mathEval(result));
}
}
}
}
});
}
function mathEval (exp) {
var reg = /(?:[a-z$_][a-z0-9$_]*)|(?:[;={}\[\]"'!&<>^\\?:])/ig,
valid = true;
// Detect valid JS identifier names and replace them
exp = exp.replace(reg, function ($0) {
// If the name is a direct member of Math, allow
if (Math.hasOwnProperty($0))
return "Math."+$0;
// Otherwise the expression is invalid
else
valid = false;
});
// Don't eval if our replace function flagged as invalid
if (!valid){
//console.log("Invalid arithmetic expression");
}
else{
try { return (eval(exp) == "Infinity" ? "0":eval(exp)); } catch (e) { };
}
}
The String break and then generate calculation is best way on function calculate_year ?
As you seen i am calculating amount from dynamic formulas,the problem is that there is some formulas return me Infinity because of tempRes.replace(/\s*#[^º]+º\s*/g,parseFloat(0));
#8~Cº / #27~Cº
how i can handle this ?Sorry for English
Working link
if you inspect you will see formula.
I have an object "Driver" defined at the beginning of my script as such:
function Driver(draw, name) {
this.draw = draw;
this.name = name;
}
I'm using this bit of JQuery to create new drivers:
var main = function () {
// add driver to table
$('#button').click(function ( ) {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#"+draw;
var name2 = "driver"+draw
console.log(draw2);
console.log(name2);
if($(name2).text().length > 0){
alert("That number has already been selected");}
else{$(name2).text(name);
var name2 = new Driver(draw, name);}
});
That part is working great. However, when I try later on to access those drivers, the console returns that it is undefined:
$('.print').click(function ( ) {
for(var i=1; i<60; i++){
var driverList = "driver"+i;
if($(driverList.draw>0)){
console.log(driverList);
console.log(driverList.name);
}
If you're interested, I've uploaded the entire project I'm working on to this site:
http://precisioncomputerservices.com/slideways/index.html
Basically, the bottom bit of code is just to try to see if I'm accessing the drivers in the correct manner (which, I'm obviously not). Once I know how to access them, I'm going to save them to a file to be used on a different page.
Also a problem is the If Statement in the last bit of code. I'm trying to get it to print only drivers that have actually been inputed into the form. I have a space for 60 drivers, but not all of them will be used, and the ones that are used won't be consecutive.
Thanks for helping out the new guy.
You can't use a variable to refer to a variable as you have done.
In your case one option is to use an key/value based object like
var drivers = {};
var main = function () {
// add driver to table
$('#button').click(function () {
var name = $('input[name=name]').val();
var draw = $('input[name=draw]').val();
var draw2 = "#" + draw;
var name2 = "driver" + draw
console.log(draw2);
console.log(name2);
if ($(name2).text().length > 0) {
alert("That number has already been selected");
} else {
$(name2).text(name);
drivers[name2] = new Driver(draw, name);
}
});
$('.print').click(function () {
for (var i = 1; i < 60; i++) {
var name2 = "driver" + i;
var driver = drivers[name2];
if (driver.draw > 0) {
console.log(driver);
console.log(driver.name);
}
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
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);