Javascript regex.exec() looping for no logical reason - javascript

This is quite likely the weirdest problem I've encountered in javascript and I don't even know if the title correctly describes it. I have a script that searches DOM (using getElementByTagName) for all <p> elements inside a specified container (once), and then iterates through them giving each to this function:
var re = /(>.+(<br>)?[\n\r]{0,2}\s*)+/gi;
var temp, nextp, nextptext, greenp, greenptext, curtext;
function greenChange(givenp) {
curtext = givenp.innerHTML;
var txt = re.exec(curtext);
while(txt) {
console.log(txt[0]);
temp = curtext.indexOf(txt[0]);
curtext = curtext.replace(txt[0],"");
greenp = document.createElement("p");
givenp.parentNode.insertBefore(greenp, givenp.nextSibling);
greenp.innerHTML = txt[0];
txt = re.exec(curtext);
}
}
It is supposed to extract every match into a different <p> element, and the text after it into another <p> element. I know it has a few derps (will place the paragraphs in the wrong order), and a few things I commented out and ommited here (like the part that creates <p> elements for unmatched text) I'm not asking about those, the main problem is:
If the greenp.innerHTML = txt[0]; line is like this, it loops forever, infinitely outputting the last match into the console, but what's REALLY weird is the fact that if I change it into for example greenp.innerHTML = "example";, it doesn't. Properly creates and places the <p> elements one after the other, all properly having "example" as text and finishes. The only semi-logical explanation I came up with is that the re.exec(curtext) somehow catches the newly created <p> sibling, even though it seems impossible. Does anyone have any tips what's wrong and how to fix it?
Note: If you want to see the full code, it is below. Just please note that this is my first time using clean JS to manipulate website's code. It has errors I am aware of and will fix when I get the greenChange function working. Tips are much appreciated though.
var re = /(>.+(<br>)?[\n\r]{0,2}\s*)+/gi;
var temp, nextp, nextptext, greenp, greenptext, tempsub, curtext;
function greenChange(givenp) {
curtext = givenp.innerHTML;
var txt = re.exec(curtext);
while(txt) {
console.log(txt[0]);
temp = curtext.indexOf(txt[0]);
curtext = curtext.replace(txt[0],"");
greenp = document.createElement("p");
//greenptext = document.createTextNode(txt[0]);
//greenp.appendChild(greenptext);
//nextptext = document.createTextNode(curtext.substring(temp));
//nextp.appendChild(nextptext);
givenp.parentNode.insertBefore(greenp, givenp.nextSibling);
greenp.innerHTML = txt[0];
/*if(tempsub = curtext.substring(temp)) {
nextp = document.createElement("p");
givenp.parentNode.insertBefore(nextp, givenp.nextSibling);
//nextp.innerHTML = curtext.substring(temp);
}*/
txt = re.exec(curtext);
}
}
window.onload = function() {
alert("Document loaded!");
var plist = document.getElementById("contentArea").getElementsByTagName('p');
console.log("After ploading.");
console.log(plist[0].innerHTML);
console.log("That was the test, now the real thing:");
for(var i = 0;i < plist.length;i++) {
greenChange(plist[i]);
}
}

Related

Paint certain words in google docs - Google Apps Script

I have this code below:
var textToHighlight = 'Normal';
var highLightStyle = {};
highLightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FFC0CB';
var paras = doc.getParagraphs();
var textLocation = {};
for (i=0; i<paras.lenght; i++) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(), textLocation.getEndOffsetInclusive(), highLightStyle);
}
}
With it, I want to color all the words 'normal' that appear in my document, but when I run the code, nothing happens and it doesn't accuse any error, it compiles normally.
I tried this another code:
let pinkColor = "#FFC0CB"
let pinkElements = body.findText("Normal")
let elem = pinkElements.getElement().asText();
let t = elem.getText();
elem.setForegroundColor(t.indexOf('Normal'), t.indexOf('High')+3, pinkColor)
But with the code above it paints only the first word 'Normal' that it finds, the rest remains neutral.
Does anyone know what may be happening to both codes?
Does anyone know what may be happening to both codes?
Code 1:
You made a typo, lenght should be length.
Code 2:
See my answer below.
Explanation:
You need to iterate over all elements with the particular keyword.
To achieve that you need to follow these steps:
get the first found element:
pinkElement = body.findText(searchWord);
check if an element with searchWord exists
do some code for this element
assign a new element which is the next one you found before:
pinkElement = body.findText(searchWord, pinkElement);
repeat steps 1-4 until there is no other element:
while (pinkElement != null)
Solution:
function myFunction() {
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
let pinkColor = "#FFC0CB";
let searchWord = "Normal";
let pinkElement = body.findText(searchWord);
while (pinkElement != null) {
let elem = pinkElement.getElement().asText();
let t = elem.getText();
elem.setForegroundColor(t.indexOf(searchWord), t.indexOf('High')+3, pinkColor);
pinkElement = body.findText(searchWord, pinkElement);
}
}
I'm surprised it is returning the first one. "length" is spelled wrong on this line:
for (i=0; i<paras.**lenght**; i++) {
See if changing it to ".length" fixes it. If not, there is a similar example in the Docs at Class Range you could use.

How can I create a syntax like vue js in vanilla JavaScript?

<div id="">
<span>{{msg}}</span>
</div>
Let's think msg is variable of JavaScript and now I want to get the parent tag of {{msg}} and push a new value by innerHTML, here {{msg}} working as an identity.
demo JavaScript example:
<script>
var msg = "This is update data";
{{msg}}.parentElement.innerHTML=msg;
</scritp>
This is not actual JavaScript code, only for better understanding.
You can use jquery easily to find that element and then replace the text
var msg = "This is update data";
$(`span:contains(${msg})`).html("Its New");
In javascript:
var spanTags = document.getElementsByTagName("span");
var msg = "This is update data";
var found;
for (var i = 0; i < spanTags.length; i++) {
if (spanTags[i].textContent == msg) {
found = spanTags[i];
break;
}
}
Now, you have found that element in found and you can now change its text
if (found) {
found.innerHTML = "New text";
}
The simplest approach is to treat the entire document as a string and then re-parse it when you're done.
The .innerHTML property is both an HTML decompiler and compiler depending on weather you're reading or writing to it. So for example if you have a list of variables that you want to replace in your document you can do:
let vars = {
msg: msg, // pass value as variable
test_number: 10, // pass value as number
test_str: 'hello' // pass value as string
};
let htmlText = document.body.innerHTML;
// find each var (assuming the syntax is {{var_name}})
// and replace with its value:
for (let var in vars) {
let pattern = '\\{\\{\\s*' + var + '\\s*\\}\\}';
let regexp = new RegExp(pattern, 'g'); // 'g' to replace all
htmlText = htmlText.replace(regexp, vars[var]);
}
// Now re-parse the html text and redraw the entire page
document.body.innerHTML = htmlText;
This is a quick, simple but brutal way to implement the {{var}} syntax. As long as you've correctly specified/designed the syntax to make it impossible to appear in the middle of html tags (for example <span {{ msg > hello </ }} span>) then this should be OK.
There may be performance penalties redrawing the entire page but if you're not doing this all the time (animation) then you would generally not notice it. In any case, if you are worried about performance always benchmark your code.
A more subtle way to do this is to only operate on text nodes so we don't accidentally mess up real html tags. The key to doing this is to write your own recursive descent parser. All nodes have a .childNodes attribute and the DOM is strictly a tree (non-cyclic) so we can scan the entire DOM and search for the syntax.
I'm not going to write complete code for this because it can get quite involved but the basic idea is as follows:
const TEXT_NODE = 3;
let vars = {
msg: msg, // pass value as variable
test_number: 10, // pass value as number
test_str: 'hello' // pass value as string
};
function walkAndReplace (node) {
if (node.nodeType === TEXT_NODE) {
let text = node.nodeValue;
// Do what you need to do with text here.
// You can copy the RegExp logic from the example above
// for simple text replacement. If you need to generate
// new DOM elements such as a <span> or <a> then remove
// this node from its .parentNode, generate the necessary
// objects then add them back to the .parentNode
}
else {
if (node.childNodes.length) {
for (let i=0; i<node.childNodes.length; i++) {
walkAndReplace(node.childNodes[i]); // recurse
}
}
}
}
walkAndReplace(document.body);

How to use a same image multiple times by loading it only once when I need different id for every element

I am a newbie to programming and web developing. The project I am doing is only for practice, if my approach seems ameteur to you, please suggest any better options.
I am trying to develop a parking lot booking system. And in the UI, I want to show all the empty/filled slots (like it is while booking movies or bus tickets).
I couldn't find a top view icon of a car, so I thought of using an image instead of icon.
But as of the image, if I use say 50 images on a single page, the page will get very heavy.
But one important thing is that I need all the elements as seperate entities, only then I will be able to book them with their id(unique address). So I want 50 different divs with seperate distinct ids but want to use only one image for all the slots, or a maximum of 2 different images(keeping the directions in mind).
how to display same image multiple times using same image in javascript
I went through this answer, and found a piece of code that might be useful:
var imgSrc = 'http://lorempixel.com/100/100';
function generateImage() {
var img = document.createElement('img')
img.src = imgSrc;
return img;
}
for (var i = 0; i < 20; i++ ) {
document.body.appendChild(generateImage());
}
While I can make use of a function and a loop in javascript to create as many copies of one image, I don't know how to alot them to the different div tags with distinct ids.
use a function :)
const addMessage = (element, msg, cls) => {
const patt = new RegExp("<");
const messageElement = document.createElement("div");
if (patt.test(msg)) {
messageElement.innerHTML = msg
} else messageElement.textContent = msg;
if (cls) messageElement.classList.add(cls);
element.appendChild(messageElement);
}
const imgPath = "/somepath";
const body = document.querySelector("body");
addMessage(body, `<img src=${imgPath} class="whatever">`, "img1"); //creates new divs with classes. the 3rd arg is optional
the best approach for this is the client side already receiving all this content as a string but as it made clear that it is for study I deduce that it is not the intention to use back end to solve this problem
let allContent = '';
for (var i = 0; i < 20; i++ ) {
allContent += `<div class="wrapper-image"><img src="/path"></div>`
}
document.getElementById('idWrapper').innerHTML = allContent;
speaking in performace the browser will only download the image once, so you can use it as many times as you like, which is disruptive to the changes you make in the DOM (remove, add or edit a content)
In my example you create all the content to be displayed on the page and then add it in a single time, it is not too bad if it is performace but the ideal is to do it on the back side
in the DIV you can put an image address of a variable to do some logical type this:
let allContent = '';
let imgOne = '/oneimg';
let imgOne = '/twoImg';
for (var i = 0; i < 20; i++ ) {
if(i>10){
allContent += `<div class="wrapper-image"><img src="${imgOne}"></div>`
}else {
allContent += `<div class="wrapper-image"><img src="${twoImg}"></div>`
}
}
document.getElementById('idWrapper').innerHTML = allContent;

How to get the next element of an array with Jquery onclick

Hi all i am trying to change the html of an object from an array of htmls. But i am having problem iterating properly. I managed to make it work once
EDIT
After a few complains about the clarity of my question I will rephrase it. I have a div panel called .trpanel and a button called #trigger2 (it is a next button). Then I have a series of divs with texts that contain translations. I want when I press the button (called next) to cycle through the translations one by one on the trpanel.
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i <= ltranslation.length; i++){
if (i==7){i=0;}
$(".trpanel").html.ltranslation[i]; or ???//replace().ltranslation[]+i??? the code throws errors
}
});
I am quite new to Javascript and i am getting a bit confused with the types of objects and arrays and loops. I managed once to add the htmls but without replacing them ... so they all came one after the other. The i tried to change the code and it hasn't worked since. Any help will be greatly appreciated.
A lot of guessing, but seems like you are trying to do this :
var trans = $('[id^="translation-"]'),
idx = 0;
$("#trigger2").on('click',function(){
$(".trpanel").html( trans.eq(idx).html() );
idx = idx > 6 ? 0 : idx+1;
});
FIDDLE
I think you are trying to do this:
if (i == 7) {
i = 0; // I don't really know why you are doing this, but it will reset the loop
}
$(".trpanel").html(ltranslation[i]); //I'm passing ltranslation[i] to the html method. Instead of .html.ltranslation[i].
}
Also, without seeing any html, I'm not sure but I think you may want to iterate over .trpanel ?
Something like:
$(".trpanel").eq(i).html(ltranslation[i]);
Another thing (so you can make your code clearer I think). You can abstract the array population in a function, like this:
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).html();
});
// Then you can use ltranslation
If you want to flip through several translations I would implement it that way:
var translations=["hej","hello", "hallo","hoy"];
var showTranslation=function(){
var current=0;
var len=translations.length;
return function(){
var direction=1;
if (current>=len) current=0;
$("#text").text(translations[current]);
current+=direction;
}
}();
$("#butt").on("click", showTranslation);
Fiddle: http://jsfiddle.net/Xr9fz/
Further: You should give your translations a class, so you could easily grab all of them with a single line:
$(".translation).each(function(index,value){ ltranslation.push(value); })
From the question : I managed once to add the htmls but without replacing them -
I think you want to add all of these items into $(".trpanel"). First, dont take the HTML of each element, clone the element itself :
//method ripped from Nico's answer.
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).clone();
});
Then you could append everything into the container, so add the htmls but without replacing them. append takes in an array without replacing the previous html.
$("#trigger2").off('click').on('click',function() {
$(".trpanel").append(ltranslation);
});
I don't know what exactly you're tring to do, but I've put comments in your code to help you better understand what your code is doing. The net effect of your code is this (which I doubt you want) :
$("#trigger2").off('click').on('click',function(){
$(".trpanel").html(ltranslation[7]);
});
This is your code with some comments and minor changes
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i < ltranslation.length; i++){
//if (i==7){i=0;} <-- This will cause an infinite loop won't it? are you trying to reset i? i will reset next time loop is called,
$(".trpanel").html(ltranslation[i]); //<-- this will overwrite elements with class .trpanel ltranslation.length times...
///you'll see only the value of translation[7] in the end
}
});
EDIT
To do what you want to do based on your comments, try this:
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var counter = 0;//a global counter variable
$("#trigger2").click(function(){ //eeverytime button is clicked do this
$(".trpanel").html(ltranslation[counter]); //set the html to an element of array
counter++; //increment counter
if(counter==ltranslation.length) //reset the counter if its bigger than array len
counter=0;
});

Why is wrap ignoring the last wrap?

I'm trying to turn more into a hyperlink, but it's like it totally ignores the last wrap.
$j('#sub > div[id^="post-"]').each(function() {
var sid=this.id.match(/^post-([0-9]+)$/);
var sfimg = $j(this).find("img");
var sfhh = $j(this).find("h2");
var sfpt = $j(this).find("p:not(:has(img)):eq(0)");
var more = 'more';
$j(this).html(sfimg);
$j(sfimg).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
$j(this).append(sfhh).append(sfpt);
$j(sfpt).wrap($j('<div>').attr('class', 'sfentry'));
$j(this).append('<div class="morelink">'+more+'</div>');
$j(more).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
});
You over-using the jquery function ($j(), in your case) and your doing things in the wrong order. Also, there may be cases (possibly) that $(this).find('img'), for instance, might return more than one element... Not sure of your scenario, though.
Try this (may not be perfect, but it should lean you in the right direction):
$j('#sub > div[id^="post-"]').each(function() {
var sid = this.id.match(/^post-([0-9]+)$/);
var sfimg = $j(this).find("img");
var sfhh = $j(this).find("h2");
var sfpt = $j(this).find("p:not(:has(img)):eq(0)");
var more = 'more';
sfimg.wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
$j(this).html(sfimg);
sfpt.wrap($j('<div>').attr('class', 'sfentry'));
// You do realize what you have will append the paragraph to your h2 tag, right?
// I think you want:
/*
$j(this).append(sfhh).end().append(sfpt);
*/
$j(this).append(sfhh).append(sfpt);
$j(this).append('<div class="morelink">'+more+'</div>');
$j('.morelink',this).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
});
There were all sorts of crazy things going on in that code. Remember that you need to modify the objects before appending them to another object (unless you have some unique way of identifying them after the fact, i.e. IDs).
Good luck.
Why do you expect $j(more) to match anything?

Categories