Use jQuery to Auto Escape characters from a var - javascript

First, I'm not sure I've titled my question properly. Please feel free to correct me if needed.
My Issue:
I've created a variable, in jQuery called var siteTitle. This variable is available for other .js files to use and then get passed back to the .html page.
It all works great and there are no issues except when the var siteTitle will contain certain characters that need to be escaped. (quote, single quote, and ampersand to be specific)
What I would like to do is to use a bit of jQuery that would search a particular dom element and see if it is using any of those characters and then automatically escape them.
I've searched for some similar functions and can not seem to find exactly what I need ... the closet idea I have seen is something like this. Its not exactly what I need but it is something like what I am looking for.
pathto: function(path, file) {
var rtrim = function(str, list) {
var charlist = !list ? 's\xA0': (list + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
var re = new RegExp('[' + charlist + ']+$', 'g');
return (str + '').replace(re, '');
};
So, I am trying to write a function that will automatically convert those characters to be escaped or their html equivalent.
So, if the var siteTitle is used in a dom element like this:
<h1 class="titleText">' + siteTitle + '</h1>
I need to be able to make sure that any characters get escaped in that element.
Here is a jsFiddle that shows exactly what I am trying to do ...
https://jsfiddle.net/bbyrdhouse/5jb2fdsr/1/
Any help is greatly appreciated.

Since you're using jquery, use the .text() function to set the value into your HTML. It'll escape it appropriately.
var siteTitle = 'My Site "Title"';
$my('.titleText').text(siteTitle);
Also, in your fiddle, the siteTitle variable is not what you think it is, because the 2nd quotation closes that value since it's not yet escaped. I wrapped it in single quotes in my example.
Updated fiddle

Related

Why isn't .replace() working on a large generated string from escodege.generate()?

I am attempting to generate some code using escodegen's .generate() function which gives me a string.
Unfortunately it does not remove completely the semi-colons (only on blocks of code), which is what I need it to do get rid of them myself. So I am using the the .replace() function , however the semi-colons are not removed for some reason.
Here is what I currently have:
generatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions)
const cleanGeneratedCode = generatedFile.replace(';', '')
console.log('cleanGeneratedCode ', cleanGeneratedCode) // string stays the exact same.
Am I doing something wrong or missing something perhaps?
As per MDN, if you provide a substring instead of a regex
It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
So, the output probably isn't exactly the same as the code generated, but rather the first semicolon has been removed. To remedy this, simply use a regex with the "global" flag (g). An example:
const cleanGenereatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions).replace(/;/g, '');
console.log('Clean generated code: ', cleanGeneratedCode);

Explain this use of quotes in Javascript to change a background image in CSS

I'm taking an online class and today's assignment should have taken 1/2 an hour but it took me 5. Eventually I quit trying because I couldn't figure out where I was going wrong. Upon doing my peer reviews, I saw a few examples of the correct code, and I now know I was going wrong with my use of quotation marks. But the working code looks like utter gibberish to me. Can you explain to me how this makes sense?
function upDate(previewPic){
document.getElementById('image').style.backgroundImage = "url" + "("+ previewPic.src+")";
}
I'm feeling frustrated because I spent all day searching everywhere online for how to use javascript to change a background image in CSS. I got close, but no one showed me any use of quotes that looked like this (nor did the instructor in my class). I don't know how I was supposed to be able to figure this out, nor how any of my classmates figured it out.
Would be better if you break your function into parts like this:
function upDate(previewPic) {
var src = previewPic.src;
var str = 'url(' + src + ')';
document.getElementById('image').style.backgroundImage = str;
}
Once you get better at programming, you can easily write the whole function in one statement. But ideally, you should break down your statements to make it more readable.
Also, in javascript strings there is no difference between single quotes and double quotes.
Hope that answers your question.
Let's break down the code:
function upDate(previewPic)
{
document.getElementById('image').style.backgroundImage = "url" + "("+ previewPic.src+")";
}
The first line is obviously function. The second line is calling to get an element by ID, in this case, it's simply defined as an image. The next part is stating that this is appending the style for the background image of the ID "image." From there, it is actually calling the image to append to the id. It's looking for an image with the same url as the local folder you are in, and with the name "previewPic. Fairly simple line of code. Hope that helps!
function setBackground( elemId, previewImage ){
var el = document.getElementById(elemId),
bg = "url('" + previewImage.src + "')";
el.style.backgroundImage = bg;
}
setBackground( 'image', /* previewPic here*/ );
The + is used as a string concatenator, which combines multiple strings into one
The text inside single or double quotes is considered a string, or text value (e.g., "this is some text")
In order to use quotes inside a string, you can escape them with a backslash (e.g. '\'' produces a one character string: ' ) or you can interchange double or single quotes (e.g., "'" also produces the one character string: ' ; or '"' produces " )
Edit:
I was thinking url() must take a quoted string argument (e.g., url('path/to/image.jpg')), but I forgot that was a coding standard we put in place; I think the W3C standard says it's optional

Regular expression for selecting part of string and excluding another part of string

I have one string as variable and I want to use str.replace to replace each search string hit with <span style="..."> + search string + </span>. The problem is that I do this in loop in which the search string changes and some times the search string is similar to span or style. When this happens the result could be something like this <span <span style="...">style</span>="...">search string</span> which is catastrophic. So I need someone to help my by creating regular expression which selects the search string and excludes <span style="..."> and <span> or give me an idea how to solve this.
Here is parth from my code which needs to be changed:
if ($("#search_criteria option:selected").text() == lng("note_text_txt", "note_text_txt") && $("#search_note").val().trim() != "")
{
var SearchArr = $("#search_note").val().split(" ");
for (i = 0; i < SearchArr.length;i++)
{
data["text"] = data["text"].replace(RegExp(SearchArr[i], 'g'), "<span style='color:red;'>" + SearchArr[i] + "</span>");
}
}
var SearchArr has words which need to be found in data["text"] and replaced.
I'm posting this answer to provide you a regex to match and get content between your <span>...</span>.
But, I'm not sure what exactly you want to do. You can post some comments to help me understand your fully needs so I can update the answer to give an accurate post.
For the moment, I leave you the regex and a demo below.
Matching and get content regex
<span.*?>(.*?)<\/span>
Here you can see a working example
On the other hand, you can use another option for replace the content.
Replace content regex
(<span.*?>)(.*?)(<\/span>)
Here you have the working demo
Hope to help.
If you are already using JQuery, you could replace the actual tag contents using selectors of the library.
I would think like this:
$(data['text']).find('*:contains(SearchArr[i])').text(function(index, text) {
return text.replace(SearchArr[i], '<span>');
});
Take this as an idea and example. In an actual use you should specify better the elements above selected by *. The 'all' selector combined with :contains would take a big hit on the performance.
Edit:
It will work with your plain text just as well. If you provide valid HTML for a constructor of JQuery object, the DOM element packed in JQuery object gets created and you can operate on it in any way you would on any one selected from the document. Have a look at the following example: http://jsfiddle.net/Vk7N3/1/

Javascript regular expression to find double quotes between certain characters

I'm trying to create a string that can be parsed into JSON. The string is dynamically created based on the content in a CMS.
That content could contain HTML markup with double quotes, which confuses the JSON parser. So, I need to replace the double quotes in the HTML with " without replacing the double quotes which are actually a part of the JSON structure.
My Idea is to wrap the HTML inside markers, which I could use to identify everything between these markers as the quotes I want to replace.
For instance the string I want to parse into JSON could look like this...
str = '{"key1":"XXX<div id="divId"></div>YYY", "key2":"XXX<div id="divId"></div>YYY"}';
So, I want to replace every double quote between a XXX and a YYY with a ".
Something like...
str = str.replace(/XXX(")YYY/g, '"');
Hope that made sense. Thanks for any suggestions.
Given Stack Overflow's "we don't do your homework" principles, I don't think I'm going to work through the whole solution, but I can give you some pointers in half-finished code.
var xySearch = /this regex should find any text between XXX...YYY/g;
// note the g at the end! That's important
var result;
var doubleQuoteIndices = [];
// note the single-equals. I avoid them when possible inside a "condition" statement,
// but here it sort of makes sense.
while (result = xySearch.exec(str)) {
var block = result[0];
// inside of the block, find the index in str of each double-quote, and add it
// to doubleQuoteIndices. You will likely need result.lastIndex for the absolute position.
}
// loop backwards through str (so that left-side replacements don't change right-side indexes)
// to replace the characters at each doubleQuoteIndices with the appropriate HTML.
I kind of find that as great as regex's are for certain patterns, having the programming language do some of the work is often the best solution.

Confused with Regex JS pattern

ok i do have this following data in my div
<div id="mydiv">
<!--
what is your present
<code>alert("this is my present");</code>
where?
<code>alert("here at my left hand");</code>
oh thank you! i love you!! hehe
<code>alert("welcome my honey ^^");</code>
-->
</div>
well what i need to do there is to get the all the scripts inside the <code> blocks and the html codes text nodes without removing the html comments inside. well its a homework given by my professor and i can't modify that div block..
I need to use regular expressions for this and this is what i did
var block = $.trim($("div#mydiv").html()).replace("<!--","").replace("-->","");
var htmlRegex = new RegExp(""); //I don't know what to do here
var codeRegex = new RegExp("^<code(*n)</code>$","igm");
var code = codeRegex.exec(block);
var html = "";
it really doesn't work... please don't give the exact answer.. please teach me.. thank you
I need to have the following blocks for the variable code
alert("this is my present");
alert("here at my left hand");
alert("welcome my honey ^^");
and this is the blocks i need for variable html
what is your present
where?
oh thank you! i love you!! hehe
my question is what is the regex pattern to get the results above?
Parsing HTML with a regular expression is not something you should do.
I'm sure your professor thinks he/she was really clever and that there's no way to access the DOM API and can wave a banner around and justify some minor corner-case for using regex to parse the DOM and that sometimes it's okay.
Well, no, it isn't. If you have complex code in there, what happens? Your regex breaks, and perhaps becomes a security exploit if this is ever in production.
So, here:
http://jsfiddle.net/zfp6D/
Walk the dom, get the nodeType 8 (comment) text value out of the node.
Invoke the HTML parser (that thing that browsers use to parse HTML, rather than regex, why you wouldn't use the HTML parser to parse HTML is totally beyond me, it's like saying "Yeah, I could nail in this nail with a hammer, but I think I'm going to just stomp on the nail with my foot until it goes in").
Find all the CODE elements in the newly parsed HTML.
Log them to console, or whatever you want to do with them.
First of all, you should be aware that because HTML is not a regular language, you cannot do generic parsing using regular expressions that will work for all valid inputs (generic nesting in particular cannot be expressed with regular expressions). Many parsers do use regular expressions to match individual tokens, but other algorithms need to be built around them
However, for a fixed input such as this, it's just a case of working through the structure you have (though it's still often easier to use different parsing methods than just regular expressions).
First lets get all the code:
var code = '', match = [];
var regex = new RegExp("<code>(.*?)</code>", "g");
while (match = regex.exec(content)) {
code += match[1] + "\n";
}
I assume content contains the content of the div that you've already extracted. Here the "g" flag says this is for "global" matching, so we can reuse the regex to find every match. The brackets indicate a capturing group, . means any character, * means repeated 0 or more times, and ? means "non-greedy" (see what happens without it to see what it does).
Now we can do a similar thing to get all the other bits, but this time the regex is slightly more complicated:
new RegExp("(<!--|</code>)(.*?)(-->|<code>)", "g")
Here | means "or". So this matches all the bits that start with either "start comment" or "end code" and end with "end comment" or "start code". Note also that we now have 3 sets of brackets, so the part we want to extract is match[2] (the second set).
You're doing a lot of unnecessary stuff. .html() gives you the inner contents as a string. You should be able to use regEx to grab exactly what you need from there. Also, try to stick with regEx literals (e.g. /^regexstring$/). You have to escape escape characters using new RegExp which gets really messy. You generally only want to use new RegExp when you need to put a string var into a regEx.
The match function of strings accepts regEx and returns a collection of every match when you add the global flag (e.g. /^regexstring$/g <-- note the 'g'). I would do something like this:
var block = $('#mydiv').html(), //you can set multiple vars in one statement w/commas
matches = block.match(/<code>[^<]*<\/code>/g);
//[^<]* <-- 0 or more characters that aren't '<' - google 'negative character class'
matches.join('_') //lazy way of avoiding a loop - join into a string with a safe character
.replace(/<\/*code>/g,'') //\/* 0 or more forward slashes
.split('_');//return the matches string back to array
//Now do what you want with matches. Eval (ew) or append in a script tag (ew).
//You have no control over the 'ew'. I just prefer data to scripts in strings

Categories