var tags=["div","span","body"];
for (i=0; i<=tags.length; i++){
source = source.replace(/\<\;<tags[i]/i, '<span class="tags[i]"><tags[i]</span>');
}
Basically, I'm trying to put all the opening div,span and body tags around a span with a class set accordingly. But, I am having issues getting the variables inside there.
I can put lines and lines for each different tag but considering this function is called on every key press I want to keep the code as small and efficient as possible.
Or are there other alternatives? I mean it would be even better if something along these lines was possible:
source = source.replace(/\<\;<div|<span/i, '<span class="div|span"><div|span</span>');
But, it clearly does not get me anywhere.
You can construct your regex from a string using the RegExp object:
source = source.replace(new RegExp("\\<\\;<" + tags[i], "i"), '<span class="' + tags[i] + '"><' + tags[i] + '</span>');
But your idea for an alternative is also possible by capturing the tag and referencing it in the replacement:
source = source.replace(/\<\;<(div|span|body)/i, '<span class="$1"><$1</span>');
You can use regexes with | (equivalent of OR): () are used to get the matched elements (div, span or body), and you can get them with $1
source.replace(/<(div|span|body)/i,'<span class="$1"><$1></span>')
Related
I have seen many articles about Go Arrays being used with Javascript but I am trying to do something a little different. I want to read a configuration file using Go, since it has access to the server side, and use it in a javascript function that will be rendered with the template. This is to avoid hard coding values in the JavaScript:
I want to change this:
javaString += "function isValidPrefix() {"
javaString += "forbidden_prefixes = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\" ];"
... more javascript ...
javaString += "}"
to something that puts the prefixes in a file, so that I don't have to recompile every time I want to add a prefix.
So I tried this:
var configArr []string
configArr = LoadFile("/conf.dat")
javaString += "forbidden_prefixes = [];"
for _, eachline := range configArr {
javaString += "forbidden_prefixes.push(\" + eachline + \");"
fmt.Println(eachline)
}
eachLine prints out correctly in the for loop but forbidden_prefixes contains one element + eachLine + which I am assuming is a syntax error but even if I try to retrieve the DOM element's value to check it against, the web console says the element doesn't exist. Everything worked fine with the hardcoded values. Am I doing something wrong or is it simply just not possible?
You are building a string using literals, without using the variable you intended to use. Try this:
javaString += fmt.Sprintf("forbidden_prefixes.push(\"%s\");",eachline)
The issue indeed comes from your syntax. You escaped the quotes so the + operators are actually part of the string. Here are two possible solutions:
javaString += "forbidden_prefixes.push(\"" + eachline + "\");"
Or
javaString += fmt.Sprintf("forbidden_prefixes.push(%q);", eachline)
%q adds quotes around the value it's replaced with.
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
I'm making an online text editor for a website I'm building, and I use custom tags for the markup.
To make it easier to read, the markup is highlighted by blue, which I do buy using the following function:
var imgOccurences = (informationText.match(/\[img/gi)).length;
for(var i = 0; i < imgOccurences; i++){
var imgLocation = informationText.indexOf('[img');
var endImgLocation = informationText.indexOf(']', imgLocation+1);
if(imgLocation != -1 && endImgLocation != -1){
var informationTextTemp1 = informationText.slice(0, imgLocation);
var informationTextTemp2 = informationText.slice(endImgLocation+1, -1);
var informationTextTemp3 = informationText.slice(imgLocation, endImgLocation+1);
informationTextTemp3 = "<span class='highlightWord'>"+informationTextTemp3+"</span>";
informationText = informationTextTemp1 + informationTextTemp3 + informationTextTemp2;
}
}
However the problem I face is that, when normalizing the text to HTML, I cannot use regex expressions, which I was previously using with the other tags, on the [img] tag, due to the fact that I wanted to highlight the image tag, and all of its contents, which includes a URL.
So I decided to count up all the occurrences of just the '[img' part of the [img] tag and then look for the next occurrence of ']', then slice it out of the normal text, then highlight it using a span, and then add it back to the normal text, while I put it in a for loop.
However only the first occurrence of the [img] tag is highlighted, and I am unsure as to how I should deal with this. Any help would be appreciated.
Basically I need to get everything which looks like: [img src='www.example.com/image.png']and make it look like:<span class='highlightWord'>[img src='example.com/image.png']</span> and then put it into the .innerHTML of the div called textHighlights.
Expected result:
The result I got:
You can do it much simpler since the .replace method accepts a regular expression as a parameter for the matching string.
informationText = informationText.replace(/(\[img.+?\])/gi, '<span class="highlightWord">$1</span>');
The above will replace all matches directly (by wrapping them in the span you want)
Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.
The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.
Try \" instead of ' in onClick
$(".container").append("Edit");
You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;