input value formation with double quotation marks and single quotes [duplicate] - javascript

This question already has answers here:
Escaping single quotes in JavaScript string for JavaScript evaluation
(9 answers)
Closed 4 years ago.
I have problem in the input "value".
$("#printCard").append("<input type='hidden' name='textCard' value='that aren't on the battlefield have flash. ' id='texting'>");
or JSON:
$("#demo").append("<input type='hidden' name='textCard' value='"+ infoCard.text +"' id='texting'>" );
Result:
<input name="textCard" value="that aren" t="" on="" the="" battlefield="" have="" flash.="" '="" id="texting" type="hidden">
The problem is double quotation marks and single quotes(aren't..).
This example:
The two options I have to save, double quotation marks and single quotes.
thank you all

If you don't need to support IE use template literals. TL are strings that have an easier syntax and extra properties. Here's a comparison between TL and SL (String Literal):
Syntax
SL: Wrap strings in double or single quotes. If the content of string has quotes as well, they should either be escaped by being prefixed with a backslash:
\" and \'
OR use HTML entities:
โ€˜ or ย‘ (Left Single QUOtation mark)
โ€™ or ย’ (Right Single QUOtation mark)๐ŸŸŠ
โ€œ or ย“ (Left Double QUOtation mark)
โ€ or ย” (Right Double QUOtation mark)
Note: These particular quotes represented by HTML entities are the curvy or smart quotes type and can only be used in plain text not code. The quotes used in code are straight, do not confuse them as universally accepted they are as different as a comma is to a period.
๐ŸŸŠ It's ok to use โ€™ as an apostrophe - Unicode9.0.0, ch06, pg. 276
TL: Wrap strings in backticks, also called grave accent, On a QWERTY keyboard the key is located at the top left corner `.
`template literal`
Concatenation vs. Interpolation
SL: A mess of single quotes, double quotes, and pluses:
var str = '<input id="'+ID+'" class="form-control">';
TL: Wrap variables and expressions in: ${...}:
var str = `<input id="${ID}" class="form-control">`;
Demo
var infoCard = {
text: "that arenโ€™t on the battlefield have flash."
};
$("#printCard0").append(`<input type='hidden' name='textCard' value='that arenโ€™t on the battlefield have flash.' id='texting0'>`);
$("#printCard1").append(`<input type='hidden' name='textCard' value='${infoCard.text}' id='texting1'>`);
<main id='core'>
<figure id='printCard0'></figure>
<figure id='printCard1'></figure>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I recommend using the object-based method, then you don't have to worry about special characters in HTML.
$("#printCard").append($("<input>", {
type: "hidden",
name: "textCard",
value: infoCard.text,
id: "texting"
});

Related

Wrap a given input string in double quotes if not already wrapped

Background
I need to wrap a JavaScript string in double quotes BUT only if the input string is not already wrapped in double quotes. For this question's purposes "wrapped" is considered as beginning and ending in a double quote regardless of grammar rules.
The Question
What's the best way (regex?) to wrap any input string (empty string included) in double quotes while avoiding duplicate wrapping? Solution should handle internal quotes assuming they are already escaped.
Example inputs/results:
Input:
Hello world
Result:
"Hello world"
Input:
"Hello world"
Result:
"Hello world"
Input:
A quick example says \"hello world\"
Result:
"A quick example says \"hello world\""
Input:
*empty string*
Result:
""
Input:
"Hi," he said, "How are you?"
Result: (considered "wrapped"):
"Hi," he said, "How are you?"
A short and simple way is just to test the first and last characters:
var input = // whatever
var wrapped = input;
if ('"' === wrapped || !('"' === wrapped[0] && '"' === wrapped.slice(-1)))
wrapped = '"' + wrapped + '"';
(This works even on empty strings, because ''[0] is undefined and ''.slice(-1) is '', neither of which cause a problem in the if condition.)
You don't say what to do if the input is just a single double-quote character, but I've assumed for the input '"' the output will be '"""'. If that's not what you want obviously you can modify the code above.
I would avoid using a regex. I'll assume from your examples and comments that the following preconditions hold:
internal quotes, if present, are already escaped
the string is either properly wrapped in (unescaped) double quotes or there are no unescaped double quotes (that is, there is never an unescaped double quote at one end and not the other)
If those assumptions are valid, the problem is much simpler. Just test whether the string starts with a double quote (which perforce wouldn't be escaped, since it's the first character) and whether it ends with an unescaped double quote. If only one is missing, you have a string that doesn't conform to the input assumptions. If both are missing, wrap the string; if neither is missing, the string is already wrapped.
Besides checking for an empty string, you also have to check for a string that consists entirely of one double quote.
You guessed it right. The best bay would be to use regex to wrap your string around quotes. Something like below:-
function quoteMe() {
var inpStr = document.getElementById("input");
inpStr.value = '"' + inpStr.value.replace(/"/g, '') + '"'
document.getElementById("result").innerHTML = inpStr.value;
}
<input type="text" value="" id="input" />
<input type="button" value="Quote Me!" onclick="javascript:quoteMe();">
<div id="result">
</div>
;
I would first take the string and replace double quotes then just add.
var res = str.replace('"', '');
res = '"' + res + '"'

in javascript, how do I store in a variable (coming from a database) that contains both quotes and apostrophes?

Let's say I access the database with this syntax :{column_name}: and I want to store it as a string in a javascript context. It works well using var str = ':{column_name}:' until the data contains apostrophes, same with quotes because the data may contain both quotes and apostrophes. I think it's impossible. What do you think?
You can escape both quotes and apostophes by using \" and \'. For example:
var str = '\' is an apostrophe and \" is a quote';
or
var str = "\' is an apostrophe and \" is a quote";
See the section "Special Characters" on http://www.w3schools.com/js/js_strings.asp

How to create string with multiple spaces in JavaScript

By creating a variable
var a = 'something' + ' ' + 'something'
I get this value: 'something something'.
How can I create a string with multiple spaces on it in JavaScript?
In 2022 - use ES6 Template Literals for this task.
If you need IE11 Support - use a transpiler.
let a = `something something`;
Template Literals are fast, powerful, and produce cleaner code.
If you need IE11 support and you don't have transpiler, stay strong ๐Ÿ’ช and use \xa0 - it is a NO-BREAK SPACE char.
Reference from UTF-8 encoding table and Unicode characters, you can write as below:
var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';
in ES6:
let a = 'something' + ' '.repeat(10) + 'something'
old answer:
var a = 'something' + Array(10).fill('\xa0').join('') + 'something'
number inside Array(10) can be changed to needed number of spaces
Use
It is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference being that a browser should not break (or wrap) a line of text at the point that this occupies.
var a = 'something' + '&nbsp &nbsp &nbsp &nbsp &nbsp' + 'something'
Non-breaking Space
A common character entity used in HTML is the non-breaking space ( ).
Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in
your text, the browser will remove 9 of them. To add real spaces to your text,
you can use the
character entity.
http://www.w3schools.com/html/html_entities.asp
Demo
var a = 'something' + '&nbsp &nbsp &nbsp &nbsp &nbsp' + 'something';
document.body.innerHTML = a;
With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:
let a = `something something`;
and to make multiline strings just press enter to create a new line, with no special characters:
let a = `something
something`;
The results are exactly the same as you write in the string.
In ES6 you can build strings like this:
const a = `something ${'\xa0'.repeat(10)} something`
Just add any space between ` ` and print variables inside with ${var}
You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.
Ex:
var a = '<pre>something something</pre>';
document.body.innerHTML = a;
I don't have this problem with the string variable itself, but only when the string is converted into html.
One can use replace and a regex to translate spaces into protected spaces replace(/ /g, '\xa0').
var a = 'something' + ' ' + 'something'
p1.innerHTML = a
p2.innerHTML = a.replace(/ /g, '\xa0')
<p id="p1"></p>
<p id="p2"></p>
BTW, if you input many spaces into contenteditable, they are translated as alternating sequences of spaces and protected spaces as you can try here:
<p contenteditable onkeyup="result.value = this.innerHTML">put many space into this editable paragraph and see the results in the textarea</p>
<textarea id="result"></textarea>

How to use '' in javascript inside another '' statement?

I have a problem.
I am using a javascript that call the HTML elements and now i want to add another element that also uses javascript but i dont know how to combine them.
This is the first:
list_options+='<li><input type="checkbox" value="Fuction 1 [first]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[first]</span</li>';
The secound js i need to integrate into the first:
<p>Coockie warning, <a onmouseover="nhpup.popup(' Coockie stuff text ');" style="cursor:pointer;" > read more </a>!</p>
So now if i want to combine the to like this it does not work becuse of the '' in the document:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(' TEXT THAT SHOULD GET DISPLAYED ');" style="cursor:pointer;" > ? </a>!</p></li>';
What should i do?
You can escape the single quote with a backslash \ character.
First off: when I refer to String literals I am referring to the creation of string primitives, as shown below. There are two types of strings, primitives and objects. String objects are created like new String(..).
In javascript, string literals are created with quotation marks, or double quotation marks. This means you can define a string like
str = 'a string'
or
str = "a string"
Single Quotation mark
But say you define your string with a quotation mark, like the first example, and you put the word "can't" in it. Now the definition will look like below.
str = 'this can't work'
This will cause an error, because the actual string is considered to be 'this can'. If we want to use quotation marks in a string literal defined with quotation marks, we must escape those characters, with the escape character \ before them. (NOTE: this escape character isn't displayed in the final string, or even in it, as Felix points out in the comments, and is explained in more detail below)
To get the string to actually work and print 'this can't work', this means we would have to do something like this:
str = 'this can\'t not work'
Double Quotation mark
If we define your string with a double quotation mark, like the second example, we can put quotation marks in them without having to escape it, so the following works:
str = "this can't not work"
Now, say we wanted to put a quote into the string. We can use either single or double quotation marks. If we use double quotation marks in a string literal defined with double quotation marks, we will have to escape those characters like when we used single quotation marks in a string literal defined with a single quotation mark, like so:
str = "he said \"foo bar baz\""
If you define you string literal in a single quotation mark, you don't need to escape double quotation marks within that string, like so:
str = 'he said "foo bar baz"'
programmatically creating strings
Say we have a variable that can be true or false and we want to tell a user. to do this, we can create a string variable, and add the value straight into it, like so:
var someValue = true;
var str = 'hey some value is ' + someValue + '.'
You can add to the string as much as you want or like.
Original question
It seems like you want to embed some variable into your string list_options. To do this, try something like below:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(' + SOME_VARIABLE_YOU_WANT_TO_DISPLAY + ');" style="cursor:pointer;" > ? </a>!</p></li>';
If however, you don't want to embed a variable into the string, and want to just display fixed text, try either of the following:
This uses escaped characters:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(\' TEXT THAT SHOULD GET DISPLAYED \');" style="cursor:pointer;" > ? </a>!</p></li>';
This uses double quotation marks:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(" TEXT THAT SHOULD GET DISPLAYED ");" style="cursor:pointer;" > ? </a>!</p></li>';
Escaping Characters
So, escaping characters is something you will need to learn to use when defining your strings, as some characters in strings can break the string creation. Also, there are special characters which do things in a string which you may want, like a new line(use \n), or tab character(use \t). If you want to read more about these characters, just google 'javascript escape characters', or alternatively, MDN has great documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

How to add single quote in the variable in Javascript?

I have variable var str as following:
var str = <option value="1">tea</option>;
I would like to make it as below
var quote_str = '<option value="1">tea</option>;'
Is there anyone can help me? Thanks in advance!
Edit:
I have tried the following code,however, it's not correct.
var quote_str = 'str';
I think that you want the semicolon outside the string literal:
var quote_str = '<option value="1">tea</option>';
If you mean that you want apostrophe characters inside the string also, you can use \' to put an apostrophe in a string delimited by apostrophes:
var quote_str = '\'<option value="1">tea</option>\'';
You can also use quotation marks to delimit the string. Then you don't have to escape the apostrophes, but you have to escape the quotation marks:
var quote_str = "'<option value=\"1\">tea</option>'";
If you already have a string, and want to add apostrophes around it, you concatenate strings:
var quote_str = "'" + str + "'";
Escape each single quote with a back-slash:
var quote_str = '\'<option value="1">tea</option>;\''
โ€ฆor wrap the string in quotes of a different kind (i.e. double quotes), but be sure to escape the inner double quotes as to not unintentionally close the string:
var quote_str = "'<option value=\"1\">tea</option>;'"
late update: now we have template literals, so the whole thing becomes a breeze:
var quote_str = `'<option value="1">tea</option>;'`
You can escape characters in Javascript with the \. If that's your issue
We can use the backslash () escape character to prevent JavaScript from interpreting a quote as the end of the string.
The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
Using this method, we can use apostrophes in strings built with ".
'We\'re safely using an apostrophe in single quotes.' We can also use quotation marks in strings built with ".
"Then he said, \"Hello, World!\"";
In my case, i'm unable to use the notation of ${} in rendered Javascript inside Python Mako Templates as it's already using ${} for rendering variables in Mako:
# mako template somewhere
var quote_str = `'${str}'`;
So i just wrote a small function:
# app.js ( a real Javascript file )
function singlequote(text) {
return `'${text}'`;
}
And then I use:
# mako template somewhere
var quote_str = singlequote(str);
# So i'm able to also use something like:
let btn = '<button type="button" onclick="update(' + singlequote(myid) + "," + singlequote(mystate) + ')"> Update </button>';

Categories

Resources