Problems with IF condition - javascript

I'm trying to make a website that gathers information from APIs. The following code always evaluates to 'Beep Boop Beep! I can\t find the Wikipedia page with the API! :-( \n Anyways here is more info on...'! Anyone have any ideas why?
var geoNamesWiki = result.geoNamesWiki;
for (let j = 0; j < 30; j++) {
if (geoNamesWiki.geonames[j].feature == 'country' &&
(geoNamesWiki.geonames[j].countryCode == openCage.results[0].components["ISO_3166-1_alpha-2"] ||
geoNamesWiki.geonames[j].title.includes(openCage.results[0].components.country))) {
$('#summary').html(geoNamesWiki.geonames[j].summary);
$('#wikiLink').html(geoNamesWiki.geonames[j].wikipediaUrl).attr("href", "https://" + geoNamesWiki.geonames[j].wikipediaUrl);
} else {
$('#summary').html('Beep Boop Beep! I can\t find the wikipedia page with the API! :-( \n Anyways here is more info on' + openCage.results[0].components.country + ':');
$('#wikiLink').html('https://en.wikipedia.org/wiki/' + encodeURI(openCage.results[0].components.country)).attr("href", 'https://en.wikipedia.org/wiki/' + encodeURI(openCage.results[0].components.country));
}
}

Is suspect you have a string there at var geoNamesWiki = result.geoNamesWiki;
Try parsing it to a JSON object first var geoNamesWiki = JSON.parse( result.geoNamesWiki );

I found the answer thanks to #Bekim Bacaj! I was overwriting what I had already done, so just needed to add a break on the final line of the IF part.

Related

string with '+' sign is not displayed in jquery

I have column in my database named rate but the datatype is string and has values like '2000+'. When I try to show this value using jQuery, why is it only showing 2000 without the '+' sign?
for (var j = 0; j < dtt2.length; j++) { if (dt0[i].CategoryID === dtt2[j].CategoryID) { var rate = dtt2[j].Rate; alert(rate.tostring()); $("#" + tbl).append('<tr><td>' + dtt2[j].ServiceName + '</td><td width="20%">₹ ' + rate.tostring() + '</td></tr>'); } }
this code is working when running on local host but when i am hosting on production the error comes string without + sign
Below is the code behind code-
foreach (DataRow dr in dt2.Rows)
{
ServiceRateList sd = new ServiceRateList();
sd.ServiceDetailID = Convert.ToInt32(dr["ServiceDetailID"]);
sd.ServiceName = dr["ServiceName"].ToString();
sd.CategoryID = Convert.ToInt32(dr["CategoryID"].ToString());
sd.CategoryName = dr["CategoryName"].ToString();
sd.Rate = dr["rate"].ToString();
bislist.Add(sd);
}
Note sure how you displaing plus sign in your JS codes.
But here work-around is to escape the plus sign by preceding it with a backslash.
var data = dbrawdata.replace('+', '\\+');
It would be good to answer your question add some line of your codes.
As i understood
Very simple,
var value='2000+';
value.toString(); // => '2000+'
OR
String('2000+'); // '2000+'

Compare two array and find match in Javascript

for(var i = 0; i < textList.length; i++){
for(var j = 0; j < titles.length; j++){
if(textList[i] === titles[j]){
console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
}
}
}
this is my code, but it won't return a match. I tried == and ===. But when i tested .includes() it worked. Can someone explain what's happening ?
If you are sure that all elements are in type String, you can use the method .search():
Prototype search
It will return the position of the match, if it dosent match in any position you will get -1 as return, soo > 0 it match.
I just tested your code with a very basic test example as follows:
let textList = ['book1', 'book2','book3']
let titles = ['book', ' tester', 'not_this', 'book2']
for(var i=0; i<textList.length;i++){
for(var j=0; j<titles.length;j++){
if (textList[i] === titles[j]){
console.log ("it includes my " + titles[j] + ' the match is ' +textList[i] + " counter " + i)
}
}
}
And I got the expected result it includes my book2 the match is book2 counter 1 so with this specific code I would suggest looking at you input arrays.
With regards to your question regarding why .includes() works and this doesn't, again we would need to se your input arrays but I would hazard a guess that it is something to do with the type checking within this function.
Finally, as others have suggested, there are other (more succinct) ways of achieving this with built in array functions, however your original question was about why this code in particular doesn't work so I've left these out.

Saving as CSV through google script handling newline characters

So I'm attempting to take a sheet from a Google Spreadsheet and save it as a .CSV file just like you can manually do. It is working fairly well, but I've ran into an issue with new lines/line feeds/carriage returns etc. I have used and modified Google's solution and some stack overflow resources that have meet my needs so far, however I'm stuck on this new line issue.
The Problem:
The Cause:
I will note that if I manually save the CSV file from Google Spreadsheets it looks fine, but that box you see in the cause picture is the issue I cannot resolve.
My current code:
function convertRangeToCsvFile_(csvFileName, sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
//Handle special characters
var text = data[row][col].toString();
text = text.replace(/(\r\n|\n|\r)/g," ");
for(var i = 0; i < text.length; i++)
{
if(text[i] == "\'" || text[i] == "\"" || text[i] == "\\" || text[i] == "\n" || text[i] == "\r" || text[i] == "\t" || text[i] == "\b" || text[i] == "\f")
{
text = spliceSlice(text,i,0,"\\");
i++;
}
}
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + text + "\""; //Puts quotes around the data for strings.
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
}
csvFile = csv;
return csvFile;
}
catch(err) {
Logger.log(err);
}
}
As you can see I'm attempting to handle the new lines with what I have read about 'regex expressions' however, they don't seem to actually be doing anything for me. So perhaps I'm just using it wrong and then it will work, or I need to go about this differently.
EDIT: I've looked at the file in Notepad++ and determined that they are LF characters causing the problem in the middle of the rows. Where as my end of row \r\n is working fine.
Instead of .replace(/(\r\n|\n|\r)/g," ") try .replace("\n", " ").replace("\r", " "), I know it's essentially the same, but I'm currently using this solution without hiccups.
This is an old question, but I ran into it at the top of my Google search when just looking for a simple solution to handling newlines on a CSV export from Sheets.
Since it's 2022 now, you can use Sheets' pretty powerful find + replace to target all newline characters (removing them, or replacing them with a literal \n string, etc). You can then export as CSV normally.
In my example here, the "Replace with" doesn't use regex, only the search does, so I'm wanting to preserve the newlines here before export.

Adding a prefix "#" to certain string values in an array

What I'm trying to do is add a check to my for loop that searches for "value_1" or "value_3". If found, than add a "#" at the beginning of that value.
Ex: #value_1, value_2, #value_3, etc
Here's my code:
for(i=1; i < columns.length-1; i++){
currentRecordKey = columns[i].dataIndex;
if(currentRecordKey == "value_1" || "value_3") {
currentRecordKey = "#" + currentRecordKey;
}
}
Worked out in my head, but this doesn't get the job done.
Any ideas?
Cheers
It should be
for(i=1; i < columns.length-1; i++){
//icon record
var currentRecordKey = columns[i].dataIndex;
if(currentRecordKey == "value_1" || currentRecordKey == "value_3") {
currentRecordKey = "+" + currentRecordKey ;
}
columns[i].dataIndex = currentRecordKey;
}
Your error is that if you don't restate that you are checking for currentRecordKey == "value_3", JavaScript will only check if currentRecordKey is true, and any non-empty string is.
Also, I've commented out icon record which might also be a typo.
Edit: also fixed the issue explained by Jasper and made currentRecordKey a local variable.

JavaScript string modification (Probably involves regular expression)

The problem I need to solve is to shorten file paths given by the user. If you didn't know, sometimes it's not possible to enter in paths with spaces in the command prompt. You are required to either put the path in quotes or rename the paths with spaces to "abcdef~1".
Example: "C:\Some Folder\Some File.exe" should become "C:\SomeFo~1\SomeFi~1.exe" (case insensitive).
I'm making a function in JavaScript to attempt to shorten file paths using this idea.
function ShortenFilePath(FilePath){
var Sections = FilePath.split("\\")
for (Index = 0; Index < Sections.length; Index++){
while (Sections[Index].length > 6 && Sections[Index].match(" ") && !Sections[Index].match("~1")){
alert(Sections[Index])
Sections[Index] = Sections[Index].replace(" ","")
Sections[Index] = Sections[Index].substring(0,6)
Sections[Index] = Sections[Index] + "~1"
alert(Sections[Index])
}
}
var FilePath = Sections.join("\\")
alert(FilePath)
return FilePath
}
The problem is, it will leave out the file extension and spit out "C:\SomeFo~1\SomeFi~1". I need help obtaining that file extension (probably through regular expression). If you feel that this function can be optimized, please do share your thoughts.
UPDATE: I believe the problem has been resolved.
UPDATE 2: There were some problems with the previous code, so I revised it a little.
UPDATE 3: Fresh new problem. Yikes. If the name of the file itself without the extension is under 7 letters, then it will turn up as "name.e~1.exe".
UPDATE 4: I think I've finally fixed the problem. I THINK.
function ShortenFilePath(FilePath){
var Sections = FilePath.split("\\")
Sections[Sections.length - 1] = Sections[Sections.length - 1].substring(0,Sections[Sections.length - 1].lastIndexOf("."))
for (Index = 0; Index < Sections.length; Index++){
while (Index > 0 && Sections[Index].match(" ") && !Sections[Index].match("~1")){
Sections[Index] = Sections[Index].replace(/ /gm,"")
Sections[Index] = Sections[Index].substring(0,6) + "~1"
}
}
return Sections.join("\\") + FilePath.substring(FilePath.lastIndexOf("."))
}
I would use this to get the extension:
someString.substring(someString.lastIndexOf("."))
you also asked for some code review, so:
1 - Your JS conventions are a little off, it looks more like C# :) Why the capital letter in variable and method names?
2 - You said you can go with the quotes option instead of using ~1, seems easier, why did you decide not to?
3 - Why do you need something like this in your JS?
How about this:
function ShortenFilePath(FilePath){
var Sections = FilePath.split("\\")
var suffix = FilePath.match(/(\..*$)/)
for (Index = 0; Index < Sections.length; Index++){
while (Sections[Index].length > 6 && Sections[Index].match(" ") && !Sections[Index].match("~1")){
alert(Sections[Index])
Sections[Index] = Sections[Index].replace(" ","")
Sections[Index] = Sections[Index].substring(0,6)
Sections[Index] = Sections[Index] + "~1"
alert(Sections[Index])
}
}
var FilePath = Sections.join("\\") + (suffix? suffix[1] : '')
alert(FilePath)
return FilePath
}
You could use String.prototype.replace with a callback:
function ShortenFilePath(FilePath){
return FilePath.replace(/([^:\\]+)([\\|\.[^\\]+)/g, function(text,match1, match2){
return match1.length > 8 ? match1.replace(' ', '').substr(0, 6) + '~1' + match2 : match1.replace(' ', '') + match2;
});
}
I am not 100% sure that this will output excactly what you need but probably you get the idea :)
jsFiddle
Fix for Update #3 problem:
if (FilePath.lastIndexOf(".") > 6){
Sections[Index] = Sections[Index].substring(0,6) + "~1"
} else {
Sections[Index] = Sections[Index].substring(0, FilePath.lastIndexOf(".")) + "~1"
}
And btw, this:
while (Sections[Index].match(" ")){
Sections[Index] = Sections[Index].replace(" ","")
}
Should probably look like this:
Sections[Index] = Sections[Index].replace(/ /gm, "");

Categories

Resources