How can I truncate result titles? - javascript

Im using soundclouds api to echo out track information but I'd like to limit the amount of characters shown for each track title result to just 24 chars? I'd also like to be able to set both the track title and artist title to be displayed as capitalised text (first letter capital rest lowercase)
Thanks
<li>Track: ' + track.title + '<BR>Artist: '+ track.user.username + '</li>'

Try this:
function formatter(str) {
if(str.length < 24) {
return str;
} else {
return str.charAt(0).toUpperCase() + str.substr(1,23) + '..';
}
}
<li>Track: ' + formatter(track.title) + '<BR>Artist: '+ formatter(track.user.username) + '</li>'
DEMO

For part 1 of your question, look at substr method. It's a standard method on all JavaScript String objects.
For part 2, capitalizing, check out this question.

You can prepare the short title in advance, first taking the substring and making sure it is lower case:
var shortTitle = track.title.substr(0,24).toLowerCase();
Then use the following to upper case the first letter and use the rest of the lowercase string, adds ...:
// ... HTML ouput by JS ...
document.write(shortTitle.charAt(0).toUpperCase() + shortTitle.slice(1));
if (shortTitle.length > 24)
document.write('...');
// ... HTML output by JS ...
Here in an example.
You can repeat these steps for the author.

Related

SyntaxError Unexpected token if within a function

I'm currently learning javascript (by using Google Script currently), I feel like this is a simple mistake, but I can't figure out a way around it.
The code below works, if I set "var colour" to a colour code. But when I change it to an if statement I get the issue. I've tried a bunch of different formats and continued having the same issue...
For info it just gets a few rows from a spreadsheet and then formats the selected rows and displays it to the user.
//Example of part of working code:
if(Line.length == 0){
var Line = lines
.slice(1)
.filter(function(row) { return row[4] == e.message.text;})
.map(function(row) {
var colour = if(row[6]=1){return "#ff0000"};
return '<b>' + row[3] + '</b> ('+ row[1] + ' or ' +row[2] + ')' + '\n' + '<font color=' + colour + '>Region: ' + row[6] + "</font>";
});
}
There is a difference between statements and expressions.
Just like you can put apples in a basket but not baskets in an apple, you can put expressions in a statement but not a statement in expressions.
var colour = ... is a statement that expects an expression on the right-hand side of the equals sign. You can't put an if statement there. You can use a conditional operator to make a a conditional expression:
var colour = row[6] == 1 ? "#ff0000" : "#000000";
Or you can use a full if statement to execute two variant assignment statements:
var colour;
if (row[6] == 1) {
colour = "#ff0000";
} else {
colour = "#000000";
}
Note also that return #ff0000 would have returned literally "#ff0000", not the text with the colour #ff0000 as I assume you want; also note that row[6] = 1 would assign 1 to row[6], not compare it.

First character of a string fusionning with a %

So i'm sending a String with javascript to a php page :
if(cp.value!=''){
s+=cp.name +" LIKE '%"+ cp.value +"%'";
console.log(s);
if(sec.value!=''){
s+=" AND "+sec.name+" LIKE '%"+ sec.value +"%'";
console.log(s);
}
}
else{
if(sec.value!=''){disappear
s+=sec.name+" LIKE '%"+ sec.value +"%'";
}
}
console.log(s);
if(s.length!=0){
var connect = new XMLHttpRequest();
connect.onreadystatechange=function(){
if (connect.readyState==4 && connect.status==200){
var resu=connect.responseText;
console.log(resu);
var tab=document.getElementById("main_tab");
tab.innerHTML=resu;
}
};
connect.open("POST","../../Controller/stage.php",false);
connect.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
connect.send("s="+s);
}
}
The string sent is for exemple :
CP_Stage LIKE '%90%' AND secteur_stage LIKE '%ait%'
But when i print the request in the php page i have something like :
SELECT * FROM Stage WHERE CP_Stage LIKE '�%' AND secteur_stage LIKE '%ait%';
i have no idea why my first number disappear with the first %.
If anyone have an idea it would be awesome, thanks !
The percent-sign is a special charcter. Any special characters like %,&,? etc need to be encoded. Your "%90" is converted to an Ascii-Value. You have to encode these values with encodeURIComponent.
s += cp.name + " LIKE '" + encodeURIComponent("%" + cp.value + "%") + "'";
Note that encodeURIComponent does not escape the ' character. If your cp.value has an ' you have to replace it with its encoding value: %27.
By the way.. its a bad idea to send mySQL-queries from client-side - thats a major security flaw. Send only the values and build your queries on server-side.

Convert a string with function calls to an array

I need to convert this function call to a simple array[] but it's not working for some reason.
Here's the fiddle
var LongCombinedReady = $('#GeoImageLat').val(exifObject.GPSLatitude + "," + "'" + exifObject.GPSLatitudeRef + "'")
var LatCombinedReady = exifObject.GPSLongitude + "," + "'" + exifObject.GPSLongitudeRef + "'"
//an attemp to take the values and convert them to an array but it doesn't work.
var LongCombined = [LongCombinedReady];
var LatCombined = [LatCombinedReady];
I've commented it all out in the fiddle also here's an image with GeoCoords if you don't have one for testing.
Test Geotag image
Basically I read the images Geotag and then convert the tag from DMS to DD so it can be used for something like Google maps.
There are three problems:
you are missing an apply in line 49
you are applying array with one item being a string while function you are applying to expects four parameters
at line 43 LongCombinedReady is an jQuery object

.replace method in JavaScript and duplicated characters

I'm trying to use JavaScript to insert HTML ruby characters on my text. The idea is to find the kanji and replace it with the ruby character that is stored on the fgana array. My code goes like this:
for (var i = 0; i < kanji.length; i++) {
phrase = phrase.replace(kanji[i],"<ruby><rb>" + kanji[i] + "</rb><rt>" + fgana[i] + "</rt></ruby>");
}
It does that just fine when there aren't duplicated characters to be replaced, but when there are the result is different from what I except. For example, if the arrays are like this:
kanji = ["毎朝","時","時"]
fgana = ["まいあさ"、"とき"、"じ"]
And the phrase is あの時毎朝6時におきていた the result becomes:
あの<ruby><rb><ruby><rb>時</rb><rt>じ</rt></ruby></rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 時 におきていた。
Instead of the desired:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt> におきていた。
To illustrate it better, look at the rendered example:
Look at how the first 時 receives both values とき and じ while the second receives nothing. The idea is to the first be とき and the second じ (as Japanese has different readings for the same character depending on some factors).
Whats might be the failure on my code?
Thanks in advance
It fails because the char you are looking for still exists in the replaced version:
...replace(kanji[i],"<ruby><rb>" + kanji[i]...
And this one should work:
var kanji = ["毎朝", "時", "時"],
fgana = ["まいあさ", "とき", "じ"],
phrase = "あの時毎朝 6 時におきていた",
rx = new RegExp("(" + kanji.join("|") + ")", "g");
console.log(phrase.replace(rx, function (m) {
var pos = kanji.indexOf(m),
k = kanji[pos],
f = fgana[pos];
delete kanji[pos];
delete fgana[pos];
return "<ruby><rb>" + k + "</rb><rt>" + f + "</rt></ruby>"
}));
Just copy and paste into console and you get:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb><rt>じ</rt></ruby>におきていた
Above line is a bit different from your desired result thou, just not sure if you indeed want this:
...6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt>...
^^^^^ here ^ not here?

Making a value plural (Greater than, Less than) in Javascript

I have the following code:
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole" + (total_click = 1 ? + ' time' + ((total_click > 1) ? 's ' : ' ') : ''));
return false;
});
});
I'm trying to have it output as such:
Clicked once: "I cheated 1 whole time."
Clicked more than once: "I cheated X whole times."
-- With an 's' at the end of "times".
The counter is working fine, it's just the last part making the "time" or "times" show up appropriately that I am having difficulty with.
Any ideas what I'm doing wrong?
Thanks!
Here is your problem: total_click = 1. Try changing it to total_click == 1. I don't see why you have that conditional in there however, as it won't work as you expect anyway. Try $("#counter").text("I cheated " + total_click + " whole time" + ((total_click == 1) ? ' ' : 's '));
You are not using the ternary operator correctly, and also assigning total_click to 1 instead of checking its value. I would suggest moving this to a function to simplify things.
function pluralize(singular, times) {
if (times == 1) return singular;
else return singular + 's';
}
Then change the string to
var text = "I cheated " + clicks + " whole " + pluralize("time", clicks);
Here's an example.
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole " + (total_click == 1 ? "time" : "times");
return false;
});
});
It's okay to use suggested implementations for a trivial cases, however it will not scale for a bigger set of problems and will not work for multiple languages (or it will get ugly very fast).
With this in mind, I’ve created a very simple JavaScript library that can be used to pluralize words in almost any language. It transparently uses CLDR database for multiple locales. It’s API is very minimalistic and integration is extremely simple. It’s called Numerous.
I’ve also written a small introduction article to it: «How to pluralize any word in different languages using JavaScript?».
Feel free to use it in your project. I will also be glad for your feedback on it!

Categories

Resources