I'm trying to parse IRC color codes in the format \u00030 to \u000315.
I added all RGB colors to a table, and looping through them I with this:
console.log(i + ">" + '\\u0003'+i + ">" + colors[i]);
var re = new RegExp("\\u0003"+i, 'gi');
console.log(re + " > " + '</span><span style="color:' + colors[i]+ ';">');
I get this output:
tools.php:337 15>\u000315>rgb(210,210,210)
tools.php:339 /\u000315/gi > </span><span style="color:rgb(210,210,210);">
tools.php:337 14>\u000314>rgb(127,127,127)
tools.php:339 /\u000314/gi > </span><span style="color:rgb(127,127,127);">
tools.php:337 13>\u000313>rgb(255,0,255)
tools.php:339 /\u000313/gi > </span><span style="color:rgb(255,0,255);">
tools.php:337 12>\u000312>rgb(0,0,252)
And nothing changes when I do html.replace(re, "<span stuff>");
Hardcoding it down to html.replace(/\\u00314/gi, '</span><span style="color: rgb(127,127,127);">'); produces no results either..
The stuff I'm trying to parse:
\u0002\u000314:: \u00037Channel Name \u000314:: \u00030SITE: \u00034UP \u000314:: \u00030IRC BONUS: \u00034OFFLINE \u000314:: \u00030SIGNUPS: \u00034CLOSED \u000314::\u000f
I seem to be missing something. \u or \\u makes no difference, gi, g, i or none makes no difference, and all in all it seems like it's simply not parsing anything this way.
The thing I did find out is that if I drop the RegExp and thus the modifiers for just html.replace("\\u00314", '</span><span style="color: rgb(127,127,127);">'); it replaces the first occurence, but that's not enough.
Is there something obvious I'm missing?
What worked in the end is the code below. Saving the string to a variable rather than doing the +i in the function is what worked
var val = $('textarea#topic').val();
var html = "<span style=\"color: #fff;\">" + val + "</span>";
var colors = [
"rgb(0,147,0)",
"rgb(0,0,0)",
"rgb(0,0,127)",
"rgb(0,147,0)",
"rgb(255,0,0)",
"rgb(127,0,0)",
"rgb(156,0,156)",
"rgb(252,127,0)",
"rgb(255,255,0)",
"rgb(0,252,0)",
"rgb(0,147,147)",
"rgb(0,255,255)",
"rgb(0,0,252)",
"rgb(255,0,255)",
"rgb(127,127,127)",
"rgb(210,210,210)"
];
for(i = (colors.length-1); i >= 0; i--) {
var index = 0;
var str = "\\u0003"+i+"";
while((index = html.indexOf(str, index + 1)) > -1) {
html = html.replace(str, '</span><span style="color:' + colors[i]+ ';">');
console.log(str + ">" + colors[i]);
}
$('div#topictext').html(html);
done = false;
setTimeout(setTrue(), 5000);
while(!done) {
}
}
html = html.replace("\\u0002", "");
html = html.replace("\\u000f", "");
$('div#topictext').html(html);
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 have a set of urls that i need to get a specific part of . The format of the url is :
http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg
I need to get the 1234567 bit and store that in a var.
Well you can do splits
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".split("/").pop().split("_").shift()
or a regular expression
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".match(/\/(\d+)_\d+\.jpg$/).pop()
You should be able to get it to work with your JSON string by checking the URL with a function. Something like this should work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
$.get("test.php", function (data) {
// now you can work with `data`
var JSON = jQuery.parseJSON(data); // it will be an object
$.each(JSON.deals.items, function (index, value) {
//console.log( value.title + ' ' + value.description );
tr = $('<tr/>');
tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
//tr.append("<td>" + value.description + "</td>");
tr.append("<td> £" + value.price + "</td>");
tr.append("<td class='temperature'>" + value.temperature + "</td>");
tr.append("<td>" + "<a href='" + value.deal_link + "' target='_blank'>" + "View Deal</a>" + "</td>");
myvar = checkForMatches(value.deal_link);
if(myvar == false) {
myvar = value.deal_link; //if no matches, use the full link
}
tr.append("<td>" + "<a href='" + myvar + "' target='_blank'>" + "Go To Argos</a>" + "</td>");
$('table').append(tr);
});
});
Earlier, more basic examples.
You can use a regular expression to find the match.
Something like this would work:
var str = "http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg";
var res = str.match(/.*\/(.*)_1.jpg/);
alert(res[1])
If you wanted to go a little further with it, you could create a function and pass the strings you wanted to test, and it would return the matched value if found, or boolean false if no matches exist.
Something like this would work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
alert(checkForMatches("http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg"))
alert(checkForMatches("this is an invalid string"))
You can see it working here: https://jsfiddle.net/9k5m7cg0/2/
Hope that helps!
var pathArray = window.location.pathname.split( '/' );
to split 1 / 2/ 3/ 4...
So to get path 2 it would be:
var setLocation = pathArray[1];
Well This should do
function getLastFolder(){
var path = window.location.href;
var folders =path.split("/");
return folders[folders.length-1]);
}
Here's the idea: take everything that comes after the final / character, and then take everything within that substring that comes before the first _ character.
var getUrlTerm = function(url) {
var urlPcs = url.split('/');
var lastUrlPc = urlPcs[urlPcs.length - 1];
return lastUrlPc.split('_')[0];
}
You can attribute the url to an 'A' element and use javascript's built in methods to make your life easier:
var parser = document.createElement('a');
parser.href = "YOUR URL HERE";
var fileName = parser.pathname.split('/').pop();
var code = fileName.split('_')[0];
code will have the value you want.
I would use a regular expression and sense it seems you are looking for numbers you can do the regex filter for that.
var path = window.location.pathname,
regFilter = /\d*/g,
filter = regFilter.exec(path);
The regular expression \d narrows your filter search to only look for digits. And the * grabs the group of digits.
Your result is in the filter var. The only thing about this is that the exec returns an array with your original string and the returned result which will be at the 1 index so you'll have to grab it from there like so.
filter[1];
I'm having a small problem with a regexp pattern. I don't have regexp knowledge, so I couldn't solve it.
I have this text:
var text = "this (is) some (ran)dom text";
and I want to capture anything between (). So after following this tutorial I came up with this pattern:
var re = /(\(\w*\))/g;
which works fine. But what I want to do now is replace the found matches, or rather modify. I want to wrap the found matches with a span tag. So I used this code:
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
text.replace(re, spanOpen + text.match(re) + spanClose);
even though the code works, I don't get the result I want. It outputs:
as HTML
this <span style="color: silver;">(is),(ran)</span> some <span style="color: silver;">(is),(ran)</span>dom text
as text
this (is),(ran) some (is),(ran)dom text
You can check the example in fiddle. How can I fix this?
The code in fiddle:
var text = "this (is) some (ran)dom text";
var re = /(\(\w*\))/g;
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
var original = "original: " + text + "<br>";
var desired = "desired: this " +spanOpen+"(is)"+spanClose+ " some " +spanOpen+"(ran)"+spanClose+ "dom text<br>";
var output = "output: " + text.replace(re, spanOpen + text.match(re) + spanClose);
var result = original + desired + output;
document.body.innerHTML = result;
If the title is wrong or misleading, I'll change it.
The .replace() method can take a function as the 2nd parameter. That will come in handy here.
var output = "output: " + text.replace(re, function(match){
return spanOpen + match + spanClose
});
The function will be called for each individual match.
You can also use '$&' in your replace string to reference each match
var output = "output: " + text.replace(re, spanOpen + '$&' + spanClose);
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
text.match(re) is returning an array of the result, so what you can do is loop this array and replace your string with each items, like this:
var matches = text.match(re);
var output = "output: " + text;
for (var i = 0; i < matches.length; i++)
{
output = output.replace(matches[i], spanOpen + matches[i] + spanClose);
}
See this FIDDLE
I am trying to implement a search box that will search a particular play (AJAX file) for any instances of the word, if the word is found it then outputs that line. My problem is that if no results are found of the word instead of continuing to show the entire play it outputs the last line of the play only.
My function:
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", current_play_dom).each(function () {
var line = this;
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query, '<span class="query_match">' + query + '</span>');
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++
$("#mainOutput").append("<br /><p class='speaker_match'>"+ $(line).parent().find('SPEAKER').text() +"</p>");
$("#mainOutput").append("<p class='act_match'>"+ $(line).parent().parent().parent().children(':first-child').text()+"</p>");
$("#mainOutput").append("<p class='scene_match'>"+ $(line).parent().parent().children(':first-child').text() +"</p>");
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#mainOutput").append("<br>");
}
});
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#sideInfo").append("<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
Also as a side question is there a neater way to do this:
$(line).parent().parent().parent().children(':first-child')