Replace illegal character in javascript string with the legal one - javascript

how do I replace illegal character in a javascript code? I found a lot of solution to strip them off the string but none to actually keep the char there.
here an example line:
document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + eventcontent[date][i]['bannerimg'] + "' />";
So in my function, it make my "for" loop not working properly as soon as the following char are in a string: <, >, /
any help is appreciated.
regards,

You can replace characters in javascript using the replace() function. Please see this stackoverflow post.

You can have the browser automatically escape the stuff for you:
function escape(string) {
var target = document.createElement('div');
target.appendChild(document.createTextNode(string));
return target.innerHTML;
}
Then use it by:
var escapedString = escape(eventcontent[date][i]['bannerimg']);
document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + escapedString + "' />";

Related

js: please explain this variable value with 5 double quotations

Please, take a brief look at the code below:
<script type="text/javascript">
function recentpostslist(json) {
document.write('<ul class="recommended">');
var i;
var j;
for (i = 0; i < json.feed.entry.length; i++)
{
for (j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
var postUrl = "'" + json.feed.entry[i].link[j].href + "'";//bs
var postTitle = json.feed.entry[i].title.$t;
var item = "<li>" + "' + postTitle + " </li>";
document.write(item);
}
document.write('</ul>');
}
</script>
<script src="https://xxxxxxxxxx.blogspot.com/feeds/posts/summary/-/recommended?max-results=3&alt=json-in-script&callback=recentpostslist"></script>
Background info
I found this somewhere on the Internet yesterday, and have been trying to modify it a bit, since.
Variables i and j were originally declared within the for loop, as in...
for (var i = 0; i < json.feed.entry.length; i++)
{
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
...
...but after doing a bit of (beginners') reading on w3schools.com, I got the impression that they're recommending keeping the variables declaration outside the for loop. My programming skills are scant, at their very best, so truth be told, I have no idea whether my impression was right.
Then I assigned a class to the <ul> element at the beginning (3rd line).
So far, so good. I checked, and the script was still working.
What it does is list the titles of a blog's 3 latest posts that have been labeled "recommended".
Then I made an attempt to assign a class to the <li> element that's declared as a... ehm... part of the value (have I understood that right?) of the item variable on line 15:
var item = "<li>" + "' + postTitle + " </li>";
But that seems to invalidate the code, which came as no surprise, really, since it did seem like a bit of a long shot.
My question
When taking a closer look at this line of code, however, I must say I was quite baffled by all the quotation marks (single and double).
It would be greatly appreciated if someone could explain
"<a href="+ postUrl + '" target="_blank">'
Why are there 5 double quotations in total? Is it incorrect?
What function does '" target="_blank">' serve?
You're using JS to create the string <a href="some-url.html" target="_blank">
All of the quotes are necessary because you're using quotes in JS to define a string literal, but also outputting quotes in the string itself - thus, the use of single quotes around double quotes. '"' in JS creates the string ".
target="_blank" is an HTML attribute that says the target window the hyperlink opens in should be called _blank, aka, a new window.
The "<a href="+ postUrl + '" target="_blank">' as a whole statement is used to dynamically build an anchor tag <a> by reading the postUrl from the feeds json, and then append this <a> tag to your html.
The first two " quotes are used to define a string literal containing the first segment of the <a> tag, while the last two " are to contain the value of the target attribute which will be shown on the final HTML, the one in the middle (the 3rd in order) is used to close the href attribute when viewed on your HTML.
This way the rendered HTML will be as following:
<a href="http://the_postUrl_value_from_feed" target="_blank">
BTW, the statement you're using is wrong, it is missing the starting " quote of the href attribute, try updating it to be as following:
'<a href="' + postUrl + '" target="_blank">'
It's just using single quotes to avoid having to escape the literal double quotes in a double-quoted string.
'" target="_blank"'
vs
"\"target=\"_blank\""
Since the definition of postUrl includes the quotes for the attribute, your definition of item has an extra double quote in it. However, I would recommend not putting those quotes postUrl, because the quotes are not part of the URL.
If you do that, there is a missing double quote earlier in the line. You have
var item = "<li>" + "' + postTitle + " </li>";
and you should have
var item = "<li>" + '' + postTitle + " </li>";
# ^^^^^^^^^^^
# Include a literal " after the =,
(Otherwise, the quote preceding target would be extraneous and need to be removed.)
The line would be a little clearer as
var item = '<li> ' + postTitle + " </li>";
and you can blame JavaScript for not having a built-in, convenient way to interpolate values into a string. (Although, see How can I do string interpolation in JavaScript?, which suggests that this has been added. Note, I am not a Javascript programmer.
var item = `<li> ${postTitle} </li>`;
)
To answer your question I have to explain something about string variables.
Lets take a look to the code where you filled your var item:
var item = "<li>" + "' + postTitle + " </li>";
Here you're making a string variable, so the quote (double or single) has to start and end the string and has to be the same, like this:
var myVar = "My content";
Follwing the code you have a variable that will be put inside another variable, so you have to open the quote, put your string, then close your quote, put the + sinal to concat string and finish (or put another + to concat with another string/var). Example:
var myAge = "23";
var myConcatVar = "I am " + myAge + " years old";
This is the basic, about concat and string.
But you are making a HTML string, and HTML code use quotes.
So, yes, you have to use all that quotation (double and single).
Now about your code:
As you presume, you have to start a string with double or single quotation, but you have to keep this quotation when you concat. In the var item you start with double quotation but use single quotation to concat with postUrl var. Your code look like this:
var item = "<li>" + "' + postTitle + " </li>";
When he must be like this:
var item = "<li>" + "<a href='"+ postUrl + "' target='_blank'>" + postTitle + "</a></li>";
Then when you print this var, the result will be like:
<li><a href='postUrl content' target='_blank'></a></li>
As you see in the result, you have to use the single and double quotation, because the atribute href and target use quotation too.
And about the target="_blank", it will send the url in a new tab.
I'm sorry for my bad english haha, and I hope this helps.
Ok, so this line has a messed up quotation mark.
var item = "<li>" + "' + postTitle + " </li>";
Give it a try with this one:
var item = "<li>" + "<a href="+ postUrl + " target='_blank'>" + postTitle + "</a></li>";
The problem was the single quote after the postUrl +...
You are already escaping the URL properly so no need for additional quotes around postUrl.
Give it a try!
The original has three " which means one is never closed so it wouldnt work. the correct one would be
" target='_blank'"
verses
'" target="_blank"'
In javascript there are a few ways to make strings two ways are ' ' single ticks and " " double ticks.
Everytime you start a tick (", ') everything inside of it is a string until a corresponding closing tick (", ') so if you need to have a string inside of a string you can accomplish this by doing either single ticks inside of double ticks or double ticks inside of single ticks. Run this in the web console
console.log("hey 'yes'");
console.log('hey "yes"');
verses
console.log("hey "yes"");
console.log('hey 'yes'');
the last to will error because you are now saying string of hey and then variable yes with closing empty string

JavaScript: Replace last occurrence of forward slash

I've tried fiddling with
replace(/_([^_]*)$/,replacement+'$1')
from another post but can't get it to work
I have a string:
<div class="plus"></div><div class="details"></div>text1/text2
that I want to transform into
<div class="plus"></div><div class="details"></div>text1/<br>text2
but I keep getting the / in /div replaced as well
Anyone?
Edit: To be clear I want to replace the last
"/"
with
"/<br>"
only the last occurance.
I dunno... maybe I'm better off going back in my code and try to replace the slash before prepending with html...
Use lastIndexOf() method
var index = str.lastIndexOf('/');
str = str.substr(0, index + 1) + "<br>" + str.substr(index + 1);
Here is the fiddle
Try
'<div class="plus"></div><div class="details"></div>text1/text2'.replace(/(\/)([^\/]*)$/, '$1' + '<br />' + '$2' )
If you're not trying to capture the slash in the back-reference, add the slash into the text itself:
replace(/_([^_]*)$/,replacement+'$1/')
-----------------------------------^
It's easier to do that using string methods:
var index = str.lastIndexOf('/');
str = str.substr(0, index) + str.substr(index + 1);

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

jquery - assign variable inside a .html()

i++;
$("#test").html("<iframe id='i' src='arr[0]'></iframe>");
I want to assign the value of the array to the iframe source as shown here. This doesn't work however. How is this possible? Thanks
$("#test").html("<iframe id='" + i + "' src='" + arr[0] + "'></iframe>");
You need to use concatenation:
$("#test").html("<iframe id=\"" + i + "\" src=\"" + arr[0] + "\"></iframe>");
Edited to match updated question
Why your code doesn't work as expected:
$("#test").html("<iframe id='i' src='arr[0]'></iframe>");
generates the html output:
<div id="test">
<iframe id='i' src='arr[0]'></iframe>
</div>
Your variables are in fact outputted as literals, since you're not using any escaping/concatenation (see this article for JS string 101).
What you can do to make it work:
While the other answers are correct, consistently using single quotes for strings makes HTML concatenation way more fun (as attribute values should usually be in double quotes):
i++;
$("#test").html('<iframe id="' + i + '" src="' + arr[0] + '"></iframe>');
What you can do to make it work even more hassle-free for you:
It might be overkill if you need to concatenate just once. In the long run though, this approach by #Zippoxer makes your life much easier when you have to insert values into strings:
String.prototype.format = function() {
var formatted = this;
for(arg in arguments) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
Usage in your case:
$("#test").html('<iframe id="{0}" src="{1}"></iframe>'.format(i, arr[0]));
try this...
$("#test").html("<iframe id='" + i + "' src='" + arr[0] + "'></iframe>");
What you are doing with $("#test").html("<iframe id='i' src='arr[0]'></iframe>"); is setting the id to the literal character "i" and setting the src to the literal string "arr[0]" rather than the values of these variables.

issue with replace() method in javascript when replacing spaces

This is the function I am working with:
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(' ','-');
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
I can't figure out for the life of me why this function replaces the first space in h1name string with a hyphen, but not any of the subsequent ones. I tried unescaping and escaping (and then replacing %20 it stumbles upon with hyphens, but that did the same thing). I tried regular expressions for catchall whitespace and that did the same thing. I feel like I am not seeing something super fundamental here.
You need to specify a global regular expression. Otherwise it only matches the first occurrence.
// regular expression
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(/\s+/g, '-'); // matches all whitespace
// use / /g to match a single space
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
// firefox only
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(' ', '-', 'g');
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
stuff = h1name.toLowerCase().replace(/ /g, '-');
The replace function was designed to only replace the first instance of the string you are searching for. If you want to replace all instances, then using regular expressions would work better.
take a look at this page for more information.
If you were trying to replace all spaces with - your close but not quite there
The replace function in JavaScript only replaces the first value it finds that matches and quits. Here is a replaceAll function.
stuff = h1name.toLowerCase().replace(' ' + /g, '-');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
alert(stuff); //make sure this is what you want
the /g specifies replace all.

Categories

Resources