<html>
<body>
<script>
var namIn = window.prompt("Enter Senator’s State and FULL Name, separated by space:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write( namAr + "<br>" + "Length:" + namArLen);
var i;
for (i = namArLen-1; i >=0;i--)
{var result = document.write("<br>" + "<h1>" + namAr[i] + "</h1>" ); }
</script>
</body>
</html>
I used a loop to help reverse my text (done for an into to JS assginment) but the letters are going in a straight line up and down. Like:
O
L
L
E
H
(It's supposed to be a senator's name, but "hello" will do for an example)
Why is this and how can I make it look normal?
You can make it look normal by putting the letters into another variable and then writing that variable out all at once. Look at lines 6, 9 and 11 in this (tested) solution.
<script>
var namIn = window.prompt("Enter Senator’s State and FULL Name, separated by space:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write( namAr + "<br>" + "Length:" + namArLen);
var result = '';
var i;
for (i = namArLen-1; i >=0;i--) {
result = result + namAr[i];
}
document.write("<br>" + "<h1>" + result + "</h1>" );
</script>
Maybe, you should add one css rule, for example:
h1 {display: inline-block;}
And remove all of BR tags.
You are using H1 tags which create new lines
{var result = document.write( namAr[i] ); }
use a style to increase the font size
example:
http://jsfiddle.net/sanpopo/rk6Nk/
Related
Let's say I have some sentences in Google Docs. Just one sentences as an example:
"My house is on fire"
I actually changed the background color so that every verb is red and every noun blue.
Now I want to make a list with all the verbs and another one with the nouns. Unfortunately getBackgroundColor() only seems to work with paragraphs and not with single words.
My idea was, to do something like this (I didn't yet have the time to think about how to do the loop, but that's not the point here anyway):
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var colorVar = paragraphs[0].getText().match(/\w+/).getBackgroundColor(); // The regEx matches the first word. Next I want to get the background color.
Logger.log(colorVar);
}
The error message I get goes something like this:
"The function getBackgroundColor in the text object couldn't be found"
Thx for any help, or hints or comments!
You want to retrieve the text from a paragraph.
You want to retrieve each word and the background color of each word from the retrieved the text.
In this case, the color is the background color which is not getForegroundColor().
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
At first, the reason of your error is that getBackgroundColor() is the method of Class Text. In your script, getBackgroundColor() is used for the string value. By this, the error occurs.
In this answer, for achieving your goal, each character of the text retrieved from the paragraph is scanned, and each word and the background color of each word can be retrieved.
Sample script:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();
var textObj = paragraphs[0].editAsText();
var text = textObj.getText();
var res = [];
var temp = "";
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (c != " ") {
temp += c;
} else {
if (temp != "") res.push({text: temp, color: textObj.getBackgroundColor(i - 1)});
temp = "";
}
}
Logger.log(res) // result
}
When you run the script, the text of 1st paragraph is parsed. And you can see the result with res as an object.
In this sample script, the 1st paragraph is used as a test case. So if you want to retrieve the value from other paragraph, please modify the script.
References:
getBackgroundColor()
getBackgroundColor(offset)
editAsText()
If I misunderstood your question and this was not the direction you want, I apologize.
Here's a script your welcome to take a look at. It highlights text that a user selects...even individual letters. I did it several years ago just to learn more about how documents work.
function highLightCurrentSelection() {
var conclusionStyle = {};
conclusionStyle[DocumentApp.Attribute.BACKGROUND_COLOR]='#ffffff';
conclusionStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
conclusionStyle[DocumentApp.Attribute.FONT_FAMILY]='Calibri';
conclusionStyle[DocumentApp.Attribute.FONT_SIZE]=20;
conclusionStyle[DocumentApp.Attribute.BOLD]=false;
conclusionStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.LEFT;
conclusionStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT]=DocumentApp.VerticalAlignment.BOTTOM;
conclusionStyle[DocumentApp.Attribute.LINE_SPACING]=1.5;
conclusionStyle[DocumentApp.Attribute.HEIGHT]=2;
conclusionStyle[DocumentApp.Attribute.LEFT_TO_RIGHT]=true;
var br = '<br />';
var selection = DocumentApp.getActiveDocument().getSelection();
var s='';
if(selection) {
s+=br + '<strong>Elements in Current Selection</strong>';
var selectedElements = selection.getRangeElements();
for(var i=0;i<selectedElements.length;i++) {
var selElem = selectedElements[i];
var el = selElem.getElement();
var isPartial = selElem.isPartial();
if(isPartial) {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:true selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor(selStart)=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(selStart, selEnd, bgcolor)
}else {
var selStart = selElem.getStartOffset();
var selEnd = selElem.getEndOffsetInclusive();
s+=br + 'isPartial:false selStart=' + selStart + ' selEnd=' + selEnd ;
var bgcolor = (el.asText().getBackgroundColor()=='#ffff00')?'#ffffff':'#ffff00';
el.asText().setBackgroundColor(bgcolor);
}
var elType=el.getType();
s+=br + 'selectedElement[' + i + '].getType()= ' + elType;
if(elType==DocumentApp.ElementType.TEXT) {
var txt = selElem.getElement().asText().getText().slice(selStart,selEnd+1);
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + 'Type:<strong>TEXT</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span>';
s+=br + 'Length: ' + txt.length;
s+=br + '<div id="sel' + Number(i) + '" style="display:none;">';
for(var key in elattrs)
{
s+= br + '<strong>' + key + '</strong>' + ' = ' + elattrs[key];
s+=br + '<input type="text" value="' + elattrs[key] + '" id="elattr' + key + Number(i) + '" />';
s+=br + '<input id="elattrbtn' + Number(i) + '" type="button" value="Save Changes" onClick="setSelectedElementAttribute(\'' + key + '\',' + i + ');" />'
}
s+='</div>Show/Hide';
}
}
if(elType==DocumentApp.ElementType.PARAGRAPH) {
var txt = selElem.getElement().asParagraph().getText();
var elattrs = el.getAttributes();
if(elattrs)
{
s+=br + '<strong>PARAGRAPH Attributes</strong>';
s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span> Text Length= ' + txt.length;
for(var key in elattrs)
{
s+= br + key + ' = ' + elattrs[key];
}
}
}
s+='<hr width="100%"/>';
}
//var finalP=DocumentApp.getActiveDocument().getBody().appendParagraph('Total Number of Elements: ' + Number(selectedElements.length));
//finalP.setAttributes(conclusionStyle);
}else {
s+= br + 'No Elements found in current selection';
}
s+='<input type="button" value="Toggle HighLight" onclick="google.script.run.highLightCurrentSelection();"/>';
//s+='<input type="button" value="Exit" onClick="google.script.host.close();" />';
DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(800).setHeight(450).setTitle('Selected Elements'));
}
The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);
I'm currently attempting to use the Flickr API and javascript to generate a page based on a search query, in this case, dogs. When the line
var hyperLink = "https://www.flickr.com/photos/" + photo.owner + "/" + photo.id + ".jpg";
Runs it states undefined is not an object in regards to photo.owner. I am able to print out photo.owner using console.log(photo.owner) but cannot access it to merely print out the information in the url.
Full code is:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Flickr Experiment</title>
</head>
<body id ="1">
<script>
function jsonFlickrApi(rsp) {
var str = "";
str +="<h1>Doggo piccies from Flickr</h1>";
str +="<h3>Total piccies: " + rsp.photos.photo.length;
var i;
for (i = 0; i <= rsp.photos.photo.length; i++) {
var photo = rsp.photos.photo[i];
var imageTitle = photo.title;
var hyperLink = "https://www.flickr.com/photos/" + photo.owner + "/" + photo.id + ".jpg";
var imgLink = "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg";
str +="<img alt=\"" + imageTitle + "\" src=\"" + imgLink + "\"/>"
}
document.writeln(str);
}
</script>
<script src="https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXf&tags=golden-retriever&per_page=100&format=json">
</script>
</body>
</html>
Arrays are zero based. That means if an array's length is 3, then the highest index is 2. The loop condition must therefore be
i < rsp.photos.photo.length
//^^ strictly smaller, not smaller or equal
If not, you will be accessing an index (namely the length of the array) which doesn't exist, which will result in undefined, the error you are getting.
Simple example:
var arr = [1,2,3];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[arr.length]);
This is what I got so far but I`m stuck.
var s=`First JavaScript string.`;
var c=`This is second text.`;
var sc = s.concat(c);
var sp=sc.split("");
var colors=[`red`,`black`">;
for(i=0;i<sc.length;i++) {
var span=`<span style="color:`+colors[i % 2">+`;">`+sp+`</span>`;
document.write(span);
}
Don't split the string, just use sc[i] instead of sp in last line.
You are writing the text with your sp variable. What you want is the current character. In your loop you loop over every character. In this for loop the i is the index. Your sc string is actually an array of characters. Therefore sc[i] points to the current character.
If you change sp to sc[i] your code works correct.
var s = "First JavaScript string.";
var c = "This is second text.";
var sc = s.concat(c);
var colors = ['red','black'];
for (i=0; i<sc.length; i++) {
var span = '<span style="color:' + colors[i % 2] + ';">' + sc[i] + '</span>';
document.write(span);
}
However a more efficient way would be:
var s = "First JavaScript string.";
var c = "This is second text.";
var sc = s.concat(c);
var colors = ['red','black'];
var html = "";
for (i=0; i<sc.length; i++) {
html += '<span style="color:' + colors[i % 2] + ';">' +sc[i]+ '</span>';
}
document.write(html);
Fiddle at: http://jsfiddle.net/4Np9u/
Here you go:
var s = "First JavaScript string.";
var c = "This is second text.";
var sc = s.concat(c);
var colors = ['red','black'];
for (i=0; i<sc.length; i++) {
var span = '<span style="color:' + colors[i % 2] + ';">' +sc[i]+ '</span>';
document.write(span);
}
JsFiddle = http://jsfiddle.net/A24q2/
I'm wondering if someone can help me with trying to know why and possible solution to my error. I'm using JavaSript to load images, but when I test my page the src attribute is getting a / at the end of .jpg.
My console looks as follows:
loop: avatars/bugsbunnyundefined
loop: avatars/chimchim.jpg/
loop:avatars/christmastree.jpg/
loop: avatars/princess.jpg/
loop: avatars/squarepants.jpg/
loop: avatars/yosemite.jpg/
loop: avatars/wilma.jpg/
loop: avatars/coatandtie.jpg/
loop: avatars/lilymunster.jpg/
loop: avatars/georgejetson.jpg/
loop: avatars/tweety.jpg/
loop: avatars/cleveland.jpg/
//JavaScript OBJECT
var reviews = [
{ Id: "ajjhwejkssl",
Title: "The little camera that could!",
Rating: 5, Body: "text here",
CreateDate: new Date(2012,5,23,14,12,10,0),
Owner: {
Id: "kwergiueerwq",
Name: "Bugs Bunny",
Url: "./users.html?id=kwergiueerwq",
AvatarImage: "avatars/bugsbunny",
IsFeaturedReviewer: false,
CreateDate: new Date(2012,2,12,9,44,0,0)
}
}]
var data = reviews;
var newDiv = null;
var my_div = null;
var my_img = null;
var total = document.getElementById('total');
var review = $('#reviews');
$(document).ready(function(){
for (var i = 0; i < data.length; i++){
console.log("loop: " + data[i].Owner.AvatarImage + rand);
var rand = ".jpg/";
rand.replace(rand , ".jpg");
//CREATE NEW REVIEW DIV
var reviewPost = "<div class='review'><div class='clear'></div><div class='content'><div class='datePosted'>" + data[i].CreateDate + "</div><div class='avatar'><div class='header'><div class='rating'><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/><img src='images/star-sprite.png'/></div></div><div class='clear'></div><div class='title'>" + data[i].Title + "</div><div class='memberImg'><img class='userImg' src=" + data[i].Owner.AvatarImage + '.jpg'+"/></div><div id='member'><div class='reviewedBy'>Reviewed by <a href='"+data[i].Owner.Url+"' class='member'>" + data[i].Owner.Name + "</a></div><div class='membership'>Member Since " + data[i].Owner.CreateDate + "</div></div></div></div><div class='clear'></div><div class='message'>" + data[i].Body + "</div></div><div class='clear'></div>";
//adds reviewPost inside of reviews
review.append(reviewPost);
$.each(".userImag" , function (){
//console.log("data: " + data[i].Owner.AvatarImage);
$(this).attr('src', data[i].Owner.AvatarImage + 'jpg');
});
}
});
I think the problem is in
var rand = ".jpg/";
rand.replace(rand , ".jpg");
the String.replace method just returns a changed string but do NOT change the original one.
String.replace
Description
This method does not change the String object it is called on. It simply returns a new string.
Take a look at this code:
console.log("loop: " + data[i].Owner.AvatarImage + rand);
var rand = ".jpg/";
rand.replace(rand , ".jpg");
The first line you're adding "+ rand" which rand has not be defined.
The second line you are setting the rand variable
And the third line is pretty much being ignored because no variable is being assigned to it. I don't think .jpg/ is actually in your image's source.
Josh
var rand = ".jpg/";
rand.replace(rand , ".jpg");
This doesnt make any sense at all. You are asigning a variable a value and replace that variable by itself ._0
You may want something like this:
var StringContainingFilePath;
var search = ".jpg/";
var replace = ".jpg";
StringContaingingFilePath = StringContaingingFilePath.replace(search,replace);