Multiple use of backticks within Javascript - javascript

I'm having some trouble using backticks and I'm wondering if anyone can help me. I have the code below which allows me to output multiple responses. The trouble is, when I put a comma after target="_blank">here` it doesn't allow me to add further phrases. I have attempted using a backspace before the backtick to break out of it but no luck. Here is my code, I'm using Javascript and HTML.
<script>
function talk(){
var know ={
"How does this work":"I can help you find what you're looking for.",
"how does this work":"I can help you find what you're looking for.",
"contact":`You can contact us by clicking here`
};
var user = document.getElementById('userBox').value;
document.getElementById('chatLog').innerHTML = user + "<br>";
if(user in know){
document.getElementById('chatLog').innerHTML = know[user] + "<br>";
}else{
document.getElementById('chatLog').innerHTML = "I do not understand.";
}
}
</script>
To clarify, I'm needing something like this: (but obviously the comma doesn't work)
"How does this work":"I can help you find what you're looking for.",
"how does this work":"I can help you find what you're looking for.",
"contact":`You can contact us by clicking here`,
"help":`You can find help by clicking here`

As you know the use of " & ' should corresponded to each other
Double quotes around attribute values are the most common in HTML, but single quotes can also be used.
In some situations, when the attribute value itself contains double quotes, it is necessary to use single quotes:
<p title='John "ShotGun" Nelson'>
Or vice versa:
<p title="John 'ShotGun' Nelson">
The backslash (\) escape character turns special characters into string characters .
If there are extra symbols in between you can use \ backslash before them so that they don't interfere with the code and treated as symbols like this :
<p title="John \'ShotGun\' Nelson you\'re a good\\bad person">
It will be displayed like this :
John 'ShotGun' Nelson you're a good\bad person
Refer to this for more about backslash

Related

JavaScript Regex For Sentence Not Working

So I am trying to write a regex to validate a normal sentence with no weird characters other than the basic ones you would see in a sentence (e.g: .,':<>... etc) and that is no longer than 512 characters. I am struggling to figure out how to do this, even after trying to look up the appropriate documentation for it.
The test code with the regex I have right now is below, however this does not work unless I remove all special characters:
const sentence = "This is a test sentence with some special characters ./<>'...";
if (/^[\w]{1,512}$/i.test(sentence)) {
console.log("You provided a valid sentence.");
}
How do I make it so that this regex allows for basic sentence characters?
Also, are there any helpful tools that I can use to create regex's for JavaScript? Thanks in advance.
Edit: I now realize that I need to just add in all the characters that I want to allow, but now I am unsure how to do so without breaking syntax and including the ' and " characters.
const sentence = "This is a test sentence with some special characters ./<>'...";
if (/^[\w~!##$%^&*()_+{}[]:";\'<>?,./]{1,512}$/i.test(sentence)) {
console.log("You provided a valid sentence.");
}
After help from others in the comments of my original post, I managed to get what I wanted with the following code:
const sentence = "This is a test sentence with some special characters ./<>'...";
if (/^[\w~!##$%^&*()_+{}[]:";\'<>?,.\/]{1,512}$/i.test(sentence)) {
console.log("You provided a valid sentence.");
}
Thank you to those who helped me!

Using $1 as a variable in javascript

I'm trying to parse a customisable block of text, which I load from a file. Simplifying it a bit, let's say, I'm trying to convert every block of text which appears inside curly brackets into a thing you can click to be javascript-alerted with the aforementioned text.
Problem is, passing $1 into the alert. $1 doesn't play like a variable. anyway, it started OK:
var text='Information here: {Thanks for clicking the info link}';
text=text.replace(/{(.+)}/g,'[<span onclick=\"alert(\\'\$1\\')\">click me</span>]');
document.write(text);
So far, so good. I click where it says "[click me]" and the message "Thanks for clicking the info link" comes up as a javascript alert.
But sometimes I want to put a message with a " or a ' into the curly brackets.
var text='Information here: {Thanks for clicking the "info" link}';
text=text.replace(/{(.+)}/g,'[<span onclick=\"alert(\\'\$1\\')\">click me</span>]');
document.write(text);
simply fails to alert. If I 'view selection source', it gives:
Information here: [<span onclick="alert('Thanks for clicking the " info"="" link')"="">click me</span>]
I've tried every combination of escaping the " marks, but no joy.
I thought of replacing " with ", but $1 isn't a variable!
Any ideas? And yes, I do want to do this! :-)
Thanks!
Use single \ for escaping ' and although there is no need to escape " within single quoted string.
var text='Information here: {Thanks for clicking the info link}';
text=text.replace(/{(.+)}/g,'[<span onclick="alert(\'$1\')">click me</span>]');
document.write(text);
I have no idea whether my idea holds any grounds at all here as the idea popped into my head - but what if you were to use (ignoring quotes, ironically) '"' rather than attempting to escape the quotes themselves?
Edit: I'm an idiot, use (without spaces) '& quot ;'

Django. Jquery. escaping string with quotes error

In a small forum, any user can save posts. Sometimes those posts include words surrounded by quotes ( " " ). This gives me an error when I try to handle those strings with javascript.
I wrote some jquery code that uses the django variable like this:
new_text = "{{text|safe}}";
$("#text_p").text(new_text);
if I mark it as "safe" then javascript gives me a syntax error:
the text "(error here)word between quotes" the user posted
This is logical because javascript understands the quotes like this:
new_text = "this is the text "word between quotes" the user posted"
So, if I don't mark it as "safe" and let django escape the text, it doesn't give me an error, but the text looks like this:
the text "word between quotes&quot the user posted
I don't know what to do, and I guess it may not be simple cause if I use single quotes to declare the javascript variable, I will have the same problem when the user posts a text with single quotes. If I use a regex to replace double quotes and not mark the text as "text|safe", then other tags will be escaped and the text will be full of "<br /&gt" etc.
I have an idea that may work but is ugly and probably not the best option:
including the text in a <p class = "hidden"> tag and then calling it using jquery.
So, the question is, how do I solve this?, is there a better way?
Thanks in advance for your help.
EDIT:
I created a Runnable to explain it better.
Use escapejs filter.
Example:
{{ string|escapejs }}
Ok, I found a partial solution, hope it helps someone in the future. It is not an elegant solution, so, if anyone has a better option, it will be welcomed.
I included the text that has a "quoted" word inside a html hidden tag.
python-django:
text_with_quotes = 'this is a text and a word between "quotes"'
html:
<p id = "new_text" class = "hidden"> {{text_with_quotes|safe}}</p>
js:
new_text = $("#new_text").text();
$("#text_p").text(new_text);
it works. But there may be a better option using javascript and/or python.

Too many quotes within quotes -- what to do?

Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";

Generic way to Escape Quotes in Javascript Variable

I have a form where users can enter any HTML.
var title = "Cool Check This"
As you can see, the variable is having " but it can be also '. It causes an error if there is ". What is better way to fix this? Storing escaped string in database like below?
$title = str_replace('"', "'", $_REQUEST['title']); // Replace double quote with single quote as js variable above is wrapped with double quotes.
Or escape it before showing on page? Anything in jQuery like escape that can help here?
var title="Cool Check This"
Well, you cannot escape it using JavaScript because JavaScript needs to see what you want to escape and you want to escape that. If you use PHP, you can use addslashes() prior to inserting into JavaScript.
Anyways, you should be careful of allowing to insert any HTML. Wrongly escaped HTML (like allowing to insert <script>) can allow to do various dangerous stuff, like stealing all cookies.

Categories