alert(name);
The output should be 'pikkertonnode_1334187978'
The 2nd ' is to far away from the end of the text.
This is my code:
var name;
var namehelp;
// For individually tab
function refresher() {
var url = 'output.php?string=' + choice[0].innerText;
var split = url.split("[new]");
var series = "[" ;
for (var i = 1; i < split.length; i++)
{
namehelp = split[i];
var splithelp = namehelp.split(")");
namehelp = splithelp[1];
alert(namehelp);
name = "'" + namehelp + "'";
alert(name);
series = series + "{ name : " + name + " , data : data[" + (i-1) + "] }," ;
}
var url is like:
http://172.23.133.61:60080/pages/select-multiple-start/output.php?string=[new]frequency%20(Monitor%201)pikkertonnode_1334156507[new]loadvalue%20(Monitor%201)pikkertonnode_1334156507
May be your variable contains unwanted spaces.Use the following to remove the spaces
alert(name.replace(/\s/g, ""));
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'));
}
function generateBC(url, separator) {
var splitthis = url.split("/");
var MiddleBit = [];
var RemoveFirstElement = splitthis.shift();
var RemoveLastElement = splitthis.pop();
var RemoveLastElementDot = RemoveLastElement.substring(0, RemoveLastElement.indexOf('.')).toUpperCase();
var arrayLength = splitthis.length;
for (var i = 0; i < arrayLength; i++) {
var elementOk = splitthis[i].toUpperCase();
var urlOk = "<a href='/pictures/'>" + elementOk + "</a>";
MiddleBit.push(urlOk);
}
var ConMiddleBitS = String(MiddleBit).replace(/,/g , separator);
var completed = 'HOME ' + separator + ConMiddleBitS + separator + "<span class='active'>" + RemoveLastElementDot + "</span>" ;
document.write(completed);
}
generateBC("mysite.com/pictures/hotels/tens/holidays.html", " : ");
I don't know why I get
TypeError: Cannot call method 'replace' of undefined
at compareResults` on .replace() ?
Can someone please explain why, as I see nothing wrong with the above.
Thank-you!
It seems that you're trying to use a String method on an array. Have you tried joining the array and the using the replace() method?
var ConMiddleBitS = MiddleBit.join('').replace(/,/g , separator);
EDIT:
If you're trying to remove the , from the array you don't have to use replace, you can just do MiddleBit = MiddleBit.join(separator).
Hi everybody this code is used to have a list name and id of facebook friends or invited friends if executed on friend list page. I'm trying to count the character of a string in javascript but .length method return always 1. I don't understand why cause I'm counting on a string not an array.
this is my code:
var name_list;
var id_list;
var count_letter_l;
var count_name = 0;
var count_id = 0;
var inputs = document.getElementsByClassName('_2akq _1box');
for(var i=0;i<inputs.length;i++){
var name = inputs[i].getElementsByTagName('span')[0].childNodes[0].nodeValue;
var full_id = inputs[i].getAttribute("data-reactid");
var split_id = full_id.split(':');
var split_two = split_id[1].split('.');
var split_final = split_two[0];
var count_letter = split_final.length;
//console.log(count_letter);
if(name != 'null'){
name_list+= ',' + '"' + name + '"';
id_list += ',' + '"' + split_final + '"';
count_letter_l += ',' + '"' + count_letter + '"';
count_name++;
count_id++;
}
}
console.log(name_list);
console.log('------!!!!!!!!------');
console.log(id_list);
console.log('names = ' + count_name);
console.log('id = ' + count_id);
console.log('letters for esch field = ' + count_letter_l);
I wish to count the character of every id cause in my case when I grab the ids I have some "0" and "1" in the and of the list. I don't know why and I wish to cut them out of the list.
This is an element of _2akq _1box class. you can see it if open firefox firbug and look at facebook front-end html code while you are displaying the friends list
<span class="_2akq _1box" data-reactid=".5q.2.0.0.0.0:0:1:$1543522353.0.0.$2.$text.0.0">
<span data-reactid=".5q.2.0.0.0.0:0:1:$1543522353.0.0.$2.$text.0.0.0">Laura Casali</span>
</span>
the console tell me:
letters for esch field = undefined,"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1".....
tnx for help
Again some Problems.
I' get some values of a Textfield ,shown like them:
134.45 987.46 -89.10
224.67 127.26 -19.12
764.32 187.96 -78.25
...and so on...
I'm get them with
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text();
}
i need them in
1;134.45;987.46;-89.10< br /><<< yes also the break - it will written in a .TXT file >>>
2;224.67;127.26;-19.12< br />
3;764.32;187.96;-78.25< br />
...and so on...
I couldn't figure it out how to. seems insoluble :(
The hekp from "guest271314" was perfekt. i've built it a Little more dynamic.
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text().replace(/\s+X/, "");
var arr = getNP01TableData.split(/\s+/);
var _arr = [];
var index = 1;
for (var i = 1; i <= (arr.length-1)/3; i++) {
_arr.push( i + ";" + arr[index] + ";" + arr[index + 1] + ";" + arr[index + 2] + "<br />\n");
index = index + 3;
}
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
// ... code to write it back in txt file
}
Thanks a lot # all for your Help
Well, let's look at what you've got: you have a text block, with numbers separated by spaces. That's something we can work with.
The .split(" ") function will separate the numbers and put them in an array; you could do a
getNP01TableData.split(" ") and your result will be:
[" ", "134.45 ", "987.46 ", "-89.10", "
", "224.67 ", "127.26 ", "-19.12
", "764.32 ", "187.96 ", "-78.25" ]
And that definitely looks like something you can work with. Throw that bad boy into a loop:
var text = "";
for (var i = 0; i<arr.length/3; i++) {
text = text + i;
for (j = 0; j<3; j++) {
text=text+";"+arr[3*i + j]
}
text = text+"</br";
}
That might need a little fiddling, but you get the idea. Also, the .trim() function is useful for removing unwanted whitespace.
Try
var text = "134.45 987.46 -89.10 224.67 127.26 -19.12 764.32 187.96 -78.25";
var arr = $.map(text.split(" "), function (value, index) {
return value === "" ? null : [value]
});
var _arr = [];
_arr.push("1;" + arr.slice(0, 3).join(",").replace(/,/g, ";") + "<br />");
_arr.push("2;" + arr.slice(3, 6).join(",").replace(/,/g, ";") + "<br />");
_arr.push("3;" + arr.slice(6, 9).join(",").replace(/,/g, ";") + "<br />");
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
var reader = new FileReader();
reader.addEventListener("loadend", function (e) {
console.log(e.target.result);
});
reader.readAsText(file);
jsfiddle http://jsfiddle.net/guest271314/YpBxA/
Is this the optimal way to load form data into a string and then to localStorage ?
I came up with this on my own, and I am not good in programming. It works, for what I need, but I am not sure if it's a bulletproof code?
<script>
var sg = document.getElementById("selectedGateway");
var sd = document.getElementById("selectedDestination");
var dm = document.getElementById("departureMonth");
var dd = document.getElementById("departureDay");
var dy = document.getElementById("departureYear");
var rm = document.getElementById("returnMonth");
var rd = document.getElementById("returnDay");
var ry = document.getElementById("returnYear");
var ad = document.getElementById("adults");
var ch = document.getElementById("option2");
$("#searchRequestForm").submit(function() {
var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value;
localStorage.setItem("string", string);
});
</script>
I would use something like the following so that I could deal with an object and its properties rather than a big string. Note that other than the jQuery selectors, this is pure JavaScript.
Demo: http://jsfiddle.net/grTWc/1/
var data = {
sg: $("#selectedGateway").val(),
sd: $("#selectedDestination").val()
// items here
};
localStorage.setItem("mykey", JSON.stringify(data));
To retrieve the data:
var data = JSON.parse(localStorage["mykey"]);
alert(data.sg);
See Also:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
http://api.jquery.com/jQuery.parseJSON/
I prefer a table driven approach so there is no repeated code (DRY):
var ids = [
"selectedGateway", "From: ",
"selectedDestination", "\nTo :",
"departureMonth", "\nDeparture: ",
"departureDay", "/",
"departureYear", "/",
"returnMonth", " \nReturn: ",
"returnDay", "/",
"returnYear", "/",
"adults", " \nNumber of adults: ",
"option2", " \nNumber of children: "];
var submitStr = "";
for (var i = 0; i < ids.length; i+=2) {
submitStr += ids[i+1] + document.getElementById(ids[i]).value;
}
localStorage.setItem("string", submitStr);
You could define a function such as the one below to directly get the values by id so then it would be simpler when you build your string.
function form(id) {
return document.getElementById(id).value;
}