I have received the following string from my ajax request:
As per json doc, "quotes must be escaped "
This is stored in data.description and is embedded in the template as:
''
data-title's value is used as a caption for lightbox plugin pop up. I tried the following function:
var HtmlEncode = function(s) {
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
as:
''
Now since the data.description contains multiple quotes javascript assumes them as multiple argument and throws error. I searched many other Stackoverflow posts which suggest to append the data in a div and retrieve its inner HTML but that is possible in my case.
Thanks
Change only the quotes that are the same as those will be surrounding the data-title. Like this:
var description = data.description.replace(/"/g, "'");
var template = '';
You can replace the double quotes in your string with single quotes or any other symbol in order for it to work inside double quotes.
you can do this with String.replace(/["]+/g,"'") this will replace the double quotes in the string with a single quote, the g in the reg-ex tells it to use all the string.
you can also fake it by using 2 single quotes like this String.replace(/["]+/g,"''"), and it will fake double quotes for you.
var HtmlEncode = function(s) {
return s.replace(/["]+/g,"''");
}
Solution 1
Escape it with replace and a regexp:
var HtmlEncode = function(s) {
return s.replace(/"/g, '\\"').replace(/'/g, "\\'");
}
''
Solution 2
Let jQuery doing this for you (only if you are using it).
var tpl = $('');
tpl.data('title', data.description);
Try to replace the quotes with HTML entity equivalents after which you can then safely use it on attributes.
var desc = data.description.replace(/'/g, "'").replace(/"/g, """);
''
Here's a Fiddle to demonstrate the solution.
Related
I've got something like this data that comes from API and I need to do JSON.parse this, but the problem was there were inner double quotes so I can't parse it what should I do, can I use regex or something.
const dataString = '{"EN" : "2. This English "Blha Blha" "Woo Woo" something wrong."}';
I also used this regex
replace(/(^"|"$)|"/g, "'");
but by using this regex it's replace all the double quotes with single quotes like this =>
{'EN' : '2. This English 'Blha Blha' 'Woo Woo' something wrong.'};
I only want to replace the quotes like this
{'EN' : '2. This English "Blha Blha" "Woo Woo" something wrong.'};
The thing is that single quotes are not valid symbols for JSON if they are used to wrap key/values. To make it clear - you need to escape double-quote symbols in values. A better approach is to update your API with that correction. More ugly but working way is placed below:
const dataString = '{"EN" : "2. This English "Blha Blha" "Woo Woo" something wrong."}';
const normalize = (dataString) => {
let newString = dataString;
newString = newString.replaceAll(`"`, `\\\"`);
newString = newString.replaceAll(`{\\\"`, `{"`);
newString = newString.replaceAll(`\\\"}`, `"}`);
newString = newString.replaceAll(`\\\" : \\\"`, `" : "`);
return newString;
};
console.log(JSON.parse(normalize(dataString)));
I'm trying to filter a string from a onmousemove event (tooltip).
The filtered string needs to be showed as text.
The problem is that the string looks like:
This string needs to be filtered. \r\n There is also unicode in this string \u00EB.
What I want:
This string needs to be filtered. There is also unicode in this string: ë
The HTML looks as follows:
<img onmousemove="showInfo(event,'This string needs to be filtered. \r\n There is also unicode in this string: \u00EB.');" onmouseout="hideInfo();" />
This is what I tried:
$(document).ready(function() {
$('td > img').each(function() {
var toolTip = $(this).attr('onmousemove'),
comment = toolTip.match(/([\'])(\\?.)*?\1/),
parentCell = $(this).parent();
$("div.timelineRow").css("padding", "7px");
$("<td><b>Info:</b><span> " + comment[0] + "</span></td>").insertAfter(parentCell);
$(this).insertAfter(parentCell);
});
});
Try decoding your Unicode character using JSON.parse. (Note the wrapping in double quotes to make it valid JSON).
Then replace the new lines with <br> tags to convert them into HTML line break elements (The browser won't render \r\n).
e.g.
var htmlComment = JSON.parse('"' + comment[0] + '"').replace("\r\n", "<br>");
$("<td><b>Info:</b><span> " + htmlComment + "</span></td>").insertAfter(parentCell);
I have a number of strings coming back from the database and I need to separate them into 2 lines based on a specific word that the backend person can insert in the string. (The word or symbol can be anything.)
I have tried the following:
var str = "some string some string space some string";
str = str.replace(/space/g, "\n")
console.log(str);
but the string still appears over one line only.
...
var str = "some string some stringspacesome string";
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
console.log(str);
var screenHeight = (this.state.windowHeight -90) + 'px';
return (
<div>
<Header />
<section className={"main " + this.state.color_name} style={{minHeight: screenHeight}}>
<div className="content-wrapper">
<div className="content" >
<h1>{str}</h1>
...
After the replacement, the str variable is going to be used as the contents of an h1 element.
If you want the string to be used as the contents of an HTML tag, then \n isn't the proper way to have it display on two lines. Rather, you'll need to use an html break tag of <br/>. You can either replace that into your strings, like this:
str = str.replace(/space/g, "<br/>")
Or for simplicity's sake, since you mentioned that the "space" string to replace can be anything, it seems like you could just skip the replacement altogether and use the desired replacement on the backend.
I have this url that I have to pass as a javascript string. I know that I need to escape the characters, but no matter what I do I can't seem to get it right?
var v = "www.youbigboy.com/showthread.php?t=1847";
You are using double quotes inside a string declared with double quotes. You can:
Change the double quotes inside the string to single quotes
var v = "<a href='www.youbigboy.com/showthread.php?t=1847'>www.youbigboy.com/showthread.php?t=1847</a>";
Escape the double quotes inside the string with \
var v = "www.youbigboy.com/showthread.php?t=1847";
Change the double quotes outside the string to single quotes
var v = 'www.youbigboy.com/showthread.php?t=1847';
you can use single quotes ' to differentiate internal quotes, or you can escape your internal quotes \"
The code becomes:
var v = "<a href='www.youbigboy.com/showthread.php?t=1847'>www.youbigboy.com/showthread.php?t=1847</a>";
or
var v = "www.youbigboy.com/showthread.php?t=1847";
maybe this
var url = "www.youbigboy.com/showthread.php?t=1847"; //or other dynamic url's
var sb = "<a href='" + url + "'>big boy url</a>";
source: is the + operator less performant than StringBuffer.append()
I wrote a simple helper for my template. Here's the code:
Handlebars.registerHelper('splitQuote', function (string) {
if (string.indexOf('|') !== -1) {
return string.replace('|', '<span>') + '</span>';
}
return string;
});
So I pass a string, and split the string by '|' character. I also want to put second part into span tags.
Problem is, the result that is being returned is pure text, so I get span tags like a text, not HTML.
Does anyone know what's the catch?
Tnx
You don´t need to use SafeString. Instead, use the "triple moustaches" from handlebar:
From Handlebars web site, HTML Escaping section:
Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{.
So, a simple triple quote in your html will avoid escaping:
{{{splitQuote}}}
You have to mark the string as html in your helper if you want to Handlebars not to escape it. Use Handlebars.safeString to do this. The below should suit your needs
Handlebars.registerHelper('splitQuote', function(string) {
if (string.indexOf('|') !== -1) {
return new Handlebars.SafeString(string.replace('|', '<span>') + '</span>');
}
return string;
});
As mentioned in comments you should probably escape the passed string using Handlebars.Utils.escapeExpression(string) to encode the string before you do your custom formatting. I'd recommend writing like this:
Handlebars.registerHelper('splitQuote', function(string) {
string = Handlebars.Utils.escapeExpression(string);
if (string.indexOf('|') !== -1) {
string = string.replace('|', '<span>') + '</span>';
}
return new Handlebars.SafeString(string); // mark as already escaped
});