JavaScript String Troubles - javascript

I've got a set of checkboxes that, when checked, should populate the associated points on a map.
This works great:
var type_column = "FastFood";
var searchType = type_column + " IN (-1,";
if ( $("#divType1").is(':checked')) searchType += "1,";
if ( $("#divType2").is(':checked')) searchType += "2,";
if ( $("#divType3").is(':checked')) searchType += "3,";
if ( $("#divType4").is(':checked')) searchType += "4,";
whereClause += " AND " + searchType.slice(0, searchType.length - 1) + ")";
But this doesn't:
var type_column = "FastFood";
var searchType = type_column + " IN (-1,";
if ( $("#divType1").is(':checked')) searchType += "Arbys,";
if ( $("#divType2").is(':checked')) searchType += "Burgerking,";
if ( $("#divType3").is(':checked')) searchType += "Checkers,";
if ( $("#divType4").is(':checked')) searchType += "Dairyqueen,";
whereClause += " AND " + searchType.slice(0, searchType.length - 1) + ")";
Changing "Arbys" to "a" (and so on) also doesn't work, so it's not about the number of characters. I've also tried putting in a set of single quotes around the string that doesn't include the comma. (Sadly, just using the numbers isn't an option for other, unrelated reasons.)

You probably want to use substring instead of slice. slice is for arrays, not for strings.

At all, your solution is very hacky. You should build the query not on client side. Apart of this, the following code may be better solution for you:
var type_column = "FastFood";
var whereClause = [];
if ( $("#divType1").is(':checked')) whereClause.push("Arbys");
if ( $("#divType2").is(':checked')) whereClause.push("Burgerking");
if ( $("#divType3").is(':checked')) whereClause.push("Checkers");
if ( $("#divType4").is(':checked')) whereClause.push("Dairyqueen");
whereClause += " AND " + type_column + " IN ('" + whereClause.join('\',\'') + "')";

You might want to add the search strings to an array. That way you dont need to worry about having a string like "Arbys," with a comma at the end and then stripping the last character, instead you can join the array using the comma as a delimiter:
var type_column = "FastFood";
var searchType = type_column + " IN (-1,";
var search_array = [];
if ( $("#divType1").is(':checked')) searchArray.push("Arbys");
if ( $("#divType2").is(':checked')) searchArray.push("Burgerking");
if ( $("#divType3").is(':checked')) searchArray.push("Checkers");
if ( $("#divType4").is(':checked')) searchArray.push("Dairyqueen");
whereClause += " AND " + searchType + searchArray.join(',') + ")";

Related

Current Alternative To .fontcolor() method in Javascript

I was given this task with some existing code to change the string color of each of three selector.value(s) that is output onto an input element to three different colors. The code boils the three selectors into a single output variable. Without destroying the code, I cannot figure out how to select each individual variables prior to condensing them.
If I could use the fontcolor() method, my life would be great but it's 2018 and I can't. Is there any way you can think of to solve this issue?To clarify, I need to alter the colors of the strings that belong to output(red), select1.value(blue) and select2.value(black.
Most of the action for this is happening in the parseOutput() function but I'm just stuck and don't think it's possible without rewriting the entire program.
function updateSelector(result){
var options = result.options;
var elementId = "select" + result.element;
var logger = document.getElementById('logger');
var selector = document.getElementById(elementId);
//logger.innerHTML = JSON.stringify(elementId);
selector.innerHTML = options;
selector.disabled = false;
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
plate();
function resetAll(){
for (var i = 0;i<3;i++){
var selector = document.getElementById('select' + i);
selector.disabled = true;
selector.innerHTML = "";
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
}
function finalSelection(){
var output = document.getElementById('out');
//output.focus();
output.select();
}
function plate(){
var plate = document.getElementById('plate');
plate.innerHTML = atob('Q3JhZnRlZCBieTogWmFjaGFyeSBTdGFjaG93aWFr');
}
//Adds the location as initial output, followed by divider, application, and issue if select1 is selected
//else statement added so if select0 is [Costco Website Name], to ommit the " - "
function parseOutput(){
var output = "";
if (select1.value.length > 0 && select0.value !== "[Costco Website Name]"){
output = output + ' - ' + select1.value + ' // ' + select2.value;
} else{
output = output + select1.value + ' // ' + select2.value;
}
out.value=output.trim();
}
And this is the Div that displays the output:
<div class="wide"><p><input class="wide" type="readonly" id="out" onfocus="this.select();"></p></div>
A modern replacement for fontcolor would use a span and a style (or class), e.g.:
function modernFontColor(str, color) {
return '<span style="color: ' + color + '">' + str + '</span>';
}
or
function modernFontClass(str, cls) {
return '<span class="' + cls + '">' + str + '</span>';
}
...where the class defines the styling.

Insert "and" before the last element jquery

var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
'&nbsp' + ':' + '&#160' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!

find the match at end of the string using regex in javascript

I have a string for ex "adlkup.db.com" and I want to validate the string for ".com" at the end of the string.
var x = "adlkup.db.com";
So I am trying something like
/.com$/.test(x)
and the . is interpreting to some other regex which finds a single character, except newline or line terminator
A period in a regular expression matches any character.
To make it literal, you need to escape it:
/\.com$/.test('stackoverflow.com'); // true
/\.com$/.test('stackoverflowcom'); // false
Alternatively, as Racil Hilan points out in the comments, you can also use the .lastIndexOf() method in order to check:
var string = 'stackoverflow.com';
string.lastIndexOf('.com') === string.length - 4; // true
or using the .substr() method:
'stackoverflow.com'.substr(-4) === '.com'; // true
In ECMAScript 6 this is done with endsWith:
x.endsWith(".com");
There is a polyfill for old browsers.
After reading your comments, I think you can use this better than the regex:
var value1 = "adlkup.db.com";
var value2 = "adlkup.db.com.w3Schools";
var value3 = ".com";
document.write(value1 + " " + endWithCom(value1) + "<br/>");
document.write(value2 + " " + endWithCom(value2) + "<br/>");
document.write(value3 + " " + endWithCom(value3) + "<br/>");
function endWithCom(text){
if(text.length < 5)
return false;
return (text.substr(-4) == ".com");
}
And you can easily convert it to generic function so you can pass it any ending you want to check:
var value1 = "adlkup.db.com";
var value2 = "adlkup.db.com.w3Schools";
var value3 = ".com";
var value4 = "adlkup.db.org";
document.write(value1 + " " + endWithButNotEqual(value1, ".com") + "<br/>");
document.write(value2 + " " + endWithButNotEqual(value2, ".com") + "<br/>");
document.write(value3 + " " + endWithButNotEqual(value3, ".com") + "<br/>");
document.write(value4 + " " + endWithButNotEqual(value4, ".org") + "<br/>");
function endWithButNotEqual(text, ending){
if(text.length <= ending.length)
return false;
return (text.substr(-ending.length) == ending);
}

JavaScript - Append a css tag to a certain part of string

Okay, so let's say I have a textbox that you can enter something like
Sebastian Soria 3'|12' Digano
Nam Tae-Hee 23', 45'|33' Julio Vezbek
And that textarea does this upon focusing your mouse out of it, the texarea gets read line by line and each line looks for its delimeter "|" and then splits it up and divides that in home and away scorer.
Here's a JS fiddle: http://jsfiddle.net/cu24k/
I could easily do it so if it's above 10, to scrap the last 4 characters of " XX'" and 3 do " X'" and split that up and color/bold it. But then I realized, what if they scored more than once? It would be 23', 45' or longer!
So, I thought... what if I can just take apart any apostrophe, comma and number and color/bold that.
Is there a way?
I'm not 100% sure what you were trying to do, but I threw together what I think you were going for: http://jsfiddle.net/cu24k/1/
Here is the updated JS:
$(document).ready(function () {
$('.scorers').on('change', function () {
$("#home_scorers").text("");
$("#away_scorers").text("");
var lines = $('.scorers').val().split('\n');
for (var i = 0; i < lines.length; i++) {
var split = lines[i].split('|');
// get home data
var home = split[0];
var homeIndex = home.search( /\d+\'/ );
var homeTeam = home.substr( 0, homeIndex );
var homeScore = home.substr( homeIndex );
// get away data
var away = split[1];
var awayIndex = away.lastIndexOf( "'" ) + 1;
var awayScore = away.substr( 0, awayIndex );
var awayTeam = away.substr( awayIndex );
// output data
$("#home_scorers").append(
"<div>" + homeTeam +
"<b>" + homeScore + "</b>" +
"</div>");
$("#away_scorers").append(
"<div>" +
"<b>" + awayScore + "</b>" +
awayTeam + "</div>");
}
});
});

Using a list position as a param to a function to pull certain data

function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.

Categories

Resources