Google Script: How to highlight a group of words? - javascript

I'd like to write a script for google docs to automatically highlight a set of words.
For one word I could use a script like this:
function myFunction() {
var doc = DocumentApp.openById('ID');
var textToHighlight = "TEST"
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
var paras = doc.getParagraphs();
var textLocation = {};
var i;
for (i=0; i<paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
But I need to search the text for a set of many more words and highlight them. (this is the list: https://conterest.de/fuellwoerter-liste-worte/)
How do I write a script for more words?
This seems to be a little bit too complicated:
function myFunction() {
var doc = DocumentApp.openById('ID');
var textToHighlight = "TEST"
var textToHighlight1 = "TEST1"
var highlightStyle = {};
highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
var paras = doc.getParagraphs();
var textLocation = {};
var i;
for (i=0; i<paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
for (i=0; i<paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight1);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
Thanks for your help!

You could use a nested for loop:
var words = ['TEST', 'TEST1'];
// For every word in words:
for (w = 0; w < words.length; ++w) {
// Get the current word:
var textToHighlight = words[w];
// Here is your code again:
for (i = 0; i < paras.length; ++i) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(), textLocation.getEndOffsetInclusive(), highlightStyle);
}
}
}
This way you can easily extend the array words with more words.

Related

make a link in angular custom filter

I have make a custom filter in angular to first extract this pattern #[1:abc] from a string into into abc.Here is my code
Html :
<div class="mts mbs lg-feed-content-txt" hm-read-more hm-limit="200" hm-more-text="more" hm-less-text="less" hm-dots-class="toggle-dots-grey" hm-text="{{activity.post.text | mentionParser:activity.post}}" hm-link-class="toggle-readmore"></div>
Javasctipt:
.filter('mentionParser', function() {
return function(text, res) {
var text;
var regex = /[#[0-9]+[:]([a-z|A-Z ]+)]/g;
var idSeprator = /[0-9]+/g;
var displaySeprator = /([a-z|A-Z ]+)/g;
var pattern = text.match(regex);
var uidList = [];
var textCopy = text;
var mentions = [];
if (pattern != null) {
for (var j = 0; j < pattern.length; j++) {
var name ='<a>'+ res.mentionList[j].name +'</a>';
textCopy = textCopy.replace(pattern[j], name );
}
return textCopy;
} else {
return text;
}
}
});
What i want is that to make abc name linkable

Populate form from JSON.parse

I am trying to re-populate a form from some values in localStorage. I can't quite manage the last part to get the loop to populate my name and values.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
var formInput = s[i];
console.log(s[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}
Could I get some pointers please.
Your issue is in this section of code.
var s = jsn.length-1;
console.log(s);
for (var i = 0; i < s.length; i++) {
You are setting s to the length of the jsn array minus 1, then using it as if it were jsn. I think you intended something like this.
function loadFromLocalStorage() {
PROCESS_SAVE = true;
var store = localStorage.getItem(STORE_KEY);
var jsn = JSON.parse(store);
console.log(jsn);
if(store.length === 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i];
console.log(jsn[i]);
$("form input[name='" + formInput.name +"']").val(formInput.value);
}
}

Can I use the 'in' keyword to test a property in an (tree) object

Let's say I've got the following object:
Variables.settings.backend.url = 'http://localhost';
What I would do to test is url is available, is do to the following:
if ('settings' in Variables && 'backend' in Variables.settings && 'url' in Variables.settings.backend) {
// true
}
This is quite cumbersome.
If this was PHP, i could just do
if (!empty($variables['settings']['backend']['url']) {
//true
}
Can this be done any simpler in JS?
I wrote a function to test this :
var isModuleDefined = function(moduleName) {
var d = moduleName.split(".");
var md = d[0];
for (var i = 1, len = d.length; i <= len; i++) {
if (eval("typeof " + md) !== "undefined") {
md = md + "." + d[i];
continue;
}
break;
}
return i === len + 1;
};
isModuleDefined("Variables.settings.backend.url");
but i really don't know about the cost-efficiency of that method, using eval.
Edit (Without eval..):
var isModuleDefined = function(moduleName) {
var d = moduleName.split(".");
var base = window;
for (var i = 0, len = d.length; i < len; i++) {
if (typeof base[d[i]] != "undefined") {
base = base[d[i]];
continue;
}
break;
}
return i === len;
};
Yet another variant
function isFieldExist(expression){
var fields = expression.split('.'),
cur = this;
for(var i=0; i<fields.length; i++){
if(typeof cur[fields[i]] === "undefined") return false;
cur = cur[fields[i]];
}
return true;
}
for using
isFieldExist("Variables.settings.backend.url"); // find in global scope
isFieldExist.call(Variables, "settings.backend.url"); // find in Variables

How to parse input[] values and put them into a Javascript Array

Let's say i have this:
<form id='foo'>
<input name='bar[name]' />
<input name='bar[age]' />
</form>
How can i get the values of array inputs within the form foo and put them into an associative array/object like this:
var result = {bar:{name:'blah',age:21}};
P.S. I don't want to use any frameworks for this.
I needed to do this myself and after finding this question I didn't like any of the answers: I don't like regex and the others are limited.
You can get the data variable many ways. I'll be using jQuery's serializeArray method when I implement this.
function parseInputs(data) {
var ret = {};
retloop:
for (var input in data) {
var val = data[input];
var parts = input.split('[');
var last = ret;
for (var i in parts) {
var part = parts[i];
if (part.substr(-1) == ']') {
part = part.substr(0, part.length - 1);
}
if (i == parts.length - 1) {
last[part] = val;
continue retloop;
} else if (!last.hasOwnProperty(part)) {
last[part] = {};
}
last = last[part];
}
}
return ret;
}
var data = {
"nom": "123",
"items[install][item_id_4]": "4",
"items[install][item_id_5]": "16",
"items[options][takeover]": "yes"
};
var out = parseInputs(data);
console.log('\n***Moment of truth:\n');
console.log(out);
You can map the elements to an object like this.
function putIntoAssociativeArray() {
var
form = document.getElementById("foo"),
inputs = form.getElementsByTagName("input"),
input,
result = {};
for (var idx = 0; idx < inputs.length; ++idx) {
input = inputs[idx];
if (input.type == "text") {
result[input.name] = input.value;
}
}
return result;
}
var form = document.getElementById( 'foo' );
var inputs = form.getElementsByTagName( "input" );
var regex = /(.+?)\[(.+?)\]/;
var result = {};
for( var i = 0; i < inputs.length; ++i ) {
var res = regex.exec( inputs[i].name );
if( res !== null ) {
if( typeof result[ res[1] ] == 'undefined' ) result[ res[1] ] = {};
result[ res[1] ][ res[2] ] = inputs[i].value;
}
}
var inputs = document.getElementsByTagName('input');
var field_name, value, matches, result = {};
for (var i = 0; i < inputs.length; i++) {
field_name = inputs[i].name;
value = inputs[i].value;
matches = field_name.match(/(.*?)\[(.*)\]/);
if (!results[matches[0]]) {
results[matches[0]] = {};
}
results[matches[0]][matches[1]] = value;
}
This will get you the elements:
var result = {};
var elements = document.forms.foo.getElementsByTagName("input");
for(var i = 0; i < elements.length; i++)
{
/* do whatever you need to do with each input */
}

Retrieving rich text box sharepoint in javascript

I have CustomNewForm for inserting items in the sharepoint list.
The fields are "Reason" and "Reason OverView"; both Multiple Line Rich Text fields. I need to copy some text from "Reason" to "Reason Overview".(A substring)
I tried to get this done with workflow but couldn't find a solution to get a substring of a form field.
I am trying to get the value from "Reason" field in javascript; but unable to do so.
MY CODE :: (not working)
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
alert('Hi');
Original.innerHTML=Reason.innerHTML;
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>
Any way to get this done??
I solved it using this
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
var reasonText = RTE_GetEditorDocument(Reason.id);
var reasonOverviewText = reasonText.body.innerText;
if(reasonOverviewText.length>=20)
{
reasonOverviewText = reasonOverviewText.substring(0,20)+'......';
Original.innerText = reasonOverviewText;
}
else
{
Original.innerText = reasonOverviewText;
}
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>

Categories

Resources