is there a way to avoid the nested loop in this code? - javascript

I'm building a chrome extension that lets the user replace words with tiny images. this is the code I have.
lookup=[['text','img.png']...];
var text = document.querySelectorAll('h1,h2,h3,h4,h5,p,li,td,caption,span,a')
for (let i=0; i< text.length; i++) {
var height = window.getComputedStyle(text[i]).fontSize
for (let j=0;j<lookup.length;j++){
text[i].innerHTML = text[i].innerHTML.replace(new RegExp(lookup[j][0],"gi"),"<img src=\"img/"+lookup[j][1]+"\" width=\""+height+"\" height=\""+height+"\">");
}
}
since this code has to run every time any text in the page changes I'm afraid the nested loop might cause serious performance degradation. is there anything in javascript that can avoid it?

You could create an object lookup and create a regex with alternation |. Use a function as the second parameter in replace, and use the lookup object to get the image based on the match
const lookup= { 'text': 'img.png' },
elements = document.querySelectorAll('h1,h2,h3,h4,h5,p,li,td,caption,span,a'),
regex = new RegExp(Object.keys(lookup).join("|"), 'gi')
elements.forEach(e => {
const height = window.getComputedStyle(e).fontSize;
e.innerHTML = e.innerHTML.replace(regex, m => `<img src="img/${lookup[m]}" width="${height}" />`)
})

Related

Is there a less convoluted way of writing this in JavaScript?

I'm creating an array of DOM elements (HTML) without having to look up into the DOM, like so:
const frames = [
...document.createRange()
.createContextualFragment(
new String(
new Array(options.length)
.fill()
.map((v, i) => `<div class="page"><iframe src="./renders/page-${i + 1}"></iframe></div>`)
)
)
.querySelectorAll('div')
].map((page, index) => _addPageWrappersAndBaseClasses(page, index))
Is there a more sane way of doing this?
Sure, just don't put everything on one line. Instead make sensible use of variables and line breaks.
const divStrings = new Array(options.length)
.fill()
.map((v, i) =>
`<div class="page"><iframe src="./renders/page-${i + 1}"></iframe></div>`
)
const frag = document.createRange().createContextualFragment(new String(foo))
const divs = [...frag.querySelectorAll('div')]
const frames = divs.map(_addPageWrappersAndBaseClasses)
Only change to the code above, other than the formatting and variables, is that the anonymous callback to .map at the end was extraneous. I changed it to pass the function being called directly.
You could get rid of a variable or two, so it doesn't need to be quite that drawn out, but there's not really any benefit to packing everything into a single expression.
Yes, it would be both more efficient and more concise to use regular DOM methods.
for(let i = 0; i < options.length; i++) {
const page = document.createElement("div");
page.className = "page";
const frame = document.createElement("iframe");
frame.src = `./renders/page-${i + 1}`;
page.appendChild(frame);
_addPageWrappersAndBaseClasses(page, i);
}
You should also try to avoid parsing HTML with strings in JavaScript.

Use loop and find html element's values JavaScript

I want to use vanilla js to loop through a string of html text and get its values. with jQuery I can do something like this
var str1="<div><h2>This is a heading1</h2><h2>This is a heading2</h2></div>";
$.each($(str1).find('h2'), function(index, value) {
/// console.log($(value).text());
});
using $(str) converts it to an html string as I understand it and we can then use .text() to get an element (h2)'s value.
but I want to do this within my node app on the backend rather than on the client side, because it'd be more efficient (?) and also it'd just be nice to not rely on jQuery.
Some context, I'm working on a blogging app. I want a table of contents created into an object server side.
This is another way using .innerHTML but uses the built-in iterable protocol
Here's the operations we'll need, the types they have, and a link to the documentation of that function
Create an HTML element from a text
String -> HTMLElement – provided by set Element#innerHTML
Get the text contents of an HTML element
HTMLElement -> String – provided by get Element#innerHTML
Find nodes matching a query selector
(HTMLElement, String) -> NodeList – provided by Element#querySelectorAll
Transform a list of nodes to a list of text
(NodeList, HTMLElement -> String) -> [String] – provided by Array.from
// html2elem :: String -> HTMLElement
const html2elem = html =>
{
const elem = document.createElement ('div')
elem.innerHTML = html
return elem.childNodes[0]
}
// findText :: (String, String) -> [String]
const findText = (html, selector) =>
Array.from (html2elem(html).querySelectorAll(selector), e => e.textContent)
// str :: String
const str =
"<div><h1>MAIN HEADING</h1><h2>This is a heading1</h2><h2>This is a heading2</h2></div>";
console.log (findText (str, 'h2'))
// [
// "This is a heading1",
// "This is a heading2"
// ]
// :: [String]
console.log (findText (str, 'h1'))
// [
// "MAIN HEADING"
// ]
// :: [String]
The best way to parse HTML is to use the DOM. But, if all you have is a string of HTML, according to this Stackoverflow member) you may create a "dummy" DOM element to which you'd add the string to be able to manipulate the DOM, as follows:
var el = document.createElement( 'html' );
el.innerHTML = "<html><head><title>aTitle</title></head>
<body><div><h2>This is a heading1</h2><h2>This is a heading2</h2></div>
</body</html>";
Now you have a couple of ways to access the data using the DOM, as follows:
var el = document.createElement( 'html' );
el.innerHTML = "<html><head><title>aTitle</title></head><body><div><h2>This is a heading1</h2><h2>This is a heading2</h2></div></body</html>";
// one way
el.g = el.getElementsByTagName;
var h2s = el.g("h2");
for(var i = 0, max = h2s.length; i < max; i++){
console.log(h2s[i].textContent);
if (i == max -1) console.log("\n");
}
// and another
var elementList = el.querySelectorAll("h2");
for (i = 0, max = elementList.length; i < max; i++) {
console.log(elementList[i].textContent);
}
You may also use a regular expression, as follows:
var str = '<div><h2>This is a heading1</h2><h2>This is a heading2</h2></div>';
var re = /<h2>([^<]*?)<\/h2>/g;
var match;
var m = [];
var i=0;
while ( match = re.exec(str) ) {
m.push(match.pop());
}
console.log(m);
The regex consists of an opening H2 tag followed by not a "<",followed by a closing H2 tag. The "*?" take into account zero or multiple instances of which there is at least zero or one instance.
Per Ryan of Stackoverflow:
exec with a global regular expression is meant to be used in a loop,
as it will still retrieve all matched subexpressions.
The critical part of the regex is the "g" flag as per MDN. It allows the exec() method to obtain multiple matches in a given string. In each loop iteration, match becomes an array containing one element. As each element is popped off and pushed onto m, the array m ultimately contains all the captured text values.

how to split the textarea into parts in javascript

I am trying to open the 5 urls inputted by the user in the textarea
But the array is not taking the url separately instead taking them altogether:
function loadUrls()
{
var myurl=new Array();
for(var i=0;i<5;i++)
{
myurl[i] = document.getElementById("urls").value.split('\n');
window.open(myurl[i]);
}
}
You only should need to split the text contents once. Then iterate over each item in that array. I think what you want is:
function loadUrls() {
var myurls = document.getElementById("urls").value.split('\n');
for(var i=0; i<myurls.length; i++) {
window.open(myurls[i]);
}
}
Here's a working example:
var input = document.getElementById('urls');
var button = document.getElementById('open');
button.addEventListener('click', function() {
var urls = input.value.split('\n');
urls.forEach(function(url){
window.open(url);
});
});
<button id="open">Open URLs</button>
<textarea id="urls"></textarea>
Note that nowadays browsers take extra steps to block popups. Look into developer console for errors.
There are a couple issues I see with this.
You are declaring a new Array and then adding values by iterating through 5 times. What happens if they put in more than 5? Or less?
split returns a list already of the split items. So if you have a String: this is a test, and split it by spaces it will return: [this, is, a, test]. There for you don't need to split the items and manually add them to a new list.
I would suggest doing something like:
var myUrls = document.getElementById("urls").value.split('\n');
for (var i = 0; i < myUrls.length; i++) {
window.open(myUrls[i]);
}
However, as others suggested, why not just use multiple inputs instead of a text area? It would be easier to work with and probably be more user friendly.
Basically:
document.getElementById("urls").value.split('\n');
returns an array with each line from textarea. To get the first line you must declare [0] after split the function because it will return the first item in Array, as split will be returning an Array with each line from textarea.
document.getElementById("urls").value.split('\n')[0];
Your function could simplify to:
function loadUrls(){
var MyURL = document.getElementById("urls").value.split('\n');//The lines
for(var i=0, Length = MyURL.length; Length > i; i++)
//Loop from 0 to length of URLs
window.open(
MyURL[i]//Open URL in array by current loop position (i)
)
}
Example:
line_1...
line_2...
... To:
["line_1","line_2"]

Looping over array and comparing to regex

So, I'll admit to being a bit of a JS noob, but as far as I can tell, this should be working and it is not.
Background:
I have a form with 3 list boxes. The list boxes are named app1, db1, and db2. I'm using javascript to allow the user to add additional list boxes, increasing the name tag for each additional select box.
When I add additional app named boxes, the value increments properly for each additional field. If I try to add addtional db named selects, it fails to recognize the 2nd tag on the first loop through the array. This causes me to end up with 2 elements named db2. On each subsequent tag, it is recognized properly and is properly incremented.
Here is the HTML for the db1 tag:
<select name="db1">
*options*
</select>
And db2:
<select name="db2">
*options*
</select>
The tags are identical. Here is the function that I am using to figure out the next number in the sequence (note: tag is either app or db, tags is an array of all select tag names in the DOM, if I inspect tags, it gives me ['app1', 'db1', 'db2', '']):
function return_select_name(tag, tags) {
matches = new Array();
var re = new RegExp(tag + "\\d+", "g");
for (var i = 0; i < tags.length; i++) {
var found = re.exec(tags[i]);
if (found != null) {
matches.push(found[0]);
}
}
matches = matches.sort();
index = parseInt(/\d+/.exec(matches.last())) + 1;
index = tag + index;
return index;
}
If I add an app tag, it will return 'app2'. If I search for a db tag, it will return 'db2' on the first time through, db3 on the 2nd, etc, etc.
So basically, I'm sure I'm doing something wrong here.
I'd handle it by keeping a counter for db and a counter for app to use to generate the names.
var appCounter = 1;//set this manually or initialize to 0 and
var dbCounter = 2;//use your create function to add your elements on pageload
Then, when you go to create your next tag, just increment your counter and use that as the suffix for your name:
var newAppElement = document.createElement('select');
newAppElement.name = 'app' + (++appCounter);
..
// --OR for the db element--
var newDbElement = document.createElement('select');
newDbElement.name = 'db' + (++dbCounter );
..
The problem you are getting is that regex objects are stateful. You can fix your program by putting the regex creation inside the loop.
function return_select_name(tag, tags) {
matches = new Array();
// <-- regex was here
for (var i = 0; i < tags.length; i++) {
var re = new RegExp(tag + "\\d+", "g"); //<--- now is here
var found = re.exec(tags[i]);
if (found != null) {
matches.push(found[0]);
}
}
matches = matches.sort();
index = parseInt(/\d+/.exec(matches[matches.length-1])) + 1; //<--- I dont think matches.last is portable, btw
index = tag + index;
return index;
}
In any case, if I were to do this myself, I would probably prefer to avoid the cmplicated text matching and just store the next tag indices in a variable or hash map.
Another suggestion: if you put parenthesis in your regex:
// /tag(\d+)/
var re = new RegExp(tag + "(\\d+)", "g");
Then you can use found[1] to get your number directly, without the extra step afterwards.
I know this has already been answered, but I put this together as a proof of concept.
http://jsfiddle.net/zero21xxx/LzyTf/
It's an object so you could probably reuse it in different scenarios. Obviously there are ways it could be improved, but I thought it was cool so I thought I would share.
The console.debug only works in Chrome and maybe FF.

how to get style="i want the css code" using regexp (javascript)

var text = '..<anything><anything style="color:red;">hello</anything><anything style="color:blue; font-size:1em;">hello</anything></anything>...';
or
var text = "..<anything><anything style='color:red;'>hello</anything><anything style='color:blue; font-size:1em;'>hello</anything></anything>...";
result:
array[0] = "color:red;";
array[1] = "color:blue; font-size:1em;";
Make a temporary element and use innerHTML, then getElementsByTagName and getAttribute('style') if it's a string like that.
If it's a reference to a DOM element skip the innerHTML part.
var d = document.createElement('div'),
text = '..<anything><anything style="color:red;">hello</anything><anything style="color:blue; font-size:1em;">hello</anything></anything>...',
styles = [];
d.innerHTML=text;
var els = d.getElementsByTagName('*');
for ( var i = els.length; i--; ) {
if ( els[i].getAttribute('style') ) {
styles.push( els[i].getAttribute('style') )
}
}
styles
The jQuery would be..
$(text).find('*').map(function() { return this.getAttribute('style') })
As has already been mentioned, it's not a great idea to use regular expressions for parsing HTML.
However, if you're determined to do it that way, this will do the job for you:
var matches = text.match(/\bstyle=(['"])(.*?)\1/gi);
var styles = [];
for(var i = 0; i < matches.length; i++) {
styles.push(matches[i].substring(7, matches[i].length - 1));
}
meder has already given the correct answer, but since a regex solution was desired I'll give one. All the usual warnings about parsing a nonregular language like HTML (or SGML, or XML) with regular expressions apply.
/<[a-z]+(?:\s+ [a-z]+\s*=\s*(?:[^\s"']*|"[^"]*"|'[^']*'))\s+style\s*=\s*"([^"]*)">/g

Categories

Resources