How to add single quote in the variable in Javascript? - 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>';

Related

JavaScript String replace() Method not working for NewsAPI http response text [duplicate]

I am trying to replace curly quotes:
str = '“I don’t know what you mean by ‘glory,’ ” Alice said.';
Using:
str.replace(/['"]/g,'');
Why it does not work? How can I do this?
You might have to (or prefer to) use Unicode escapes:
var goodQuotes = badQuotes.replace(/[\u2018\u2019]/g, "'");
That's for funny single quotes; the codes for double quotes are 201C and 201D.
edit — thus to completely replace all the fancy quotes:
var goodQuotes = badQuotes
.replace(/[\u2018\u2019]/g, "'")
.replace(/[\u201C\u201D]/g, '"');
It doesn't work because you're trying to replace the ASCII apostrophe (or single-quote) and quote characters with the empty string, when what's actually in your source string aren't ASCII characters.
str.replace(/[“”‘’]/g,'');
works.
Combining Pointy and Wooble's answers, if you want to replace the curly quotes with regular quotes:
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
So for example:
str = '“I don’t know what you mean by ‘glory,’ ” Alice said.';
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
console.log(str)

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 escape characters in a string

Consider below response of ajax-
function validateVar(){
$.ajax({
url:"abc.do",
datatype:"text",
success:function(response){
alert(response); //"asdjakd"fsd'f'fsf"s'dfs'df"fsdf"fsfsf""
}
});
}
I want to escape all occurrences of quotes in the response.
JSFIDDLE: https://jsfiddle.net/ashwyn/3w0aj5z7/
You can use the backslash to escape a character \. So to store your string in a variable we can write it like this.
var v = "asdjakd\"fsd\'f\'fsf\"s\'dfs\'df\"fsdf\"fsfsf";
You can't programmatically escape a string to make it valid JavaScript.
It has to be valid JavaScript to get through the JavaScript parser before it can be modified by JavaScript.
You have to fix it in the source code.
The \ character starts an escape sequence in a JavaScript string literal:
var v = "asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf";
You can use backslash to solve this
You need to add backslash for same type inverted commas(single or double).
function validateVar(){
var v = "asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf";
alert(v);
}
Update the fiddle as well, check here :: https://jsfiddle.net/3w0aj5z7/1/
You need to escape the double quotationmark " with backslash \
Your string should look like this:
"asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf"
You can include the string between '' or "" .
Then you must say to the variable where quotes aren't the closing ones with \ before it.
In this case:
var v = ' "asdjakd"fsd\'f\'fsf"s\'dfs\'df"fsdf"fsfsf" ';
before ' quote
or
var v = " \"asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf\" ";
before " quotes

How to add slash to quotes in JS string?

There is the following example of string:
var s = "abcdwq'xx'x";
How can I screen ordinary quotes, i.e. add slash? I tried to use the following code:
s.replace('/(["\'\])/g', "\\$1")
but it doesn't work. Thanks in advance
Don't put the regular expression in quotes, that makes it an ordinary string.
var s = "abcdwq'xx'x";
console.log(s.replace(/(["'])/g, "\\$1"));
Also, you were escaping the ] that ends [.
If you just want to escape single quotes, you don't need the brackets or capture group. Just do:
var s = "abcdwq'xx'x";
console.log(s.replace(/'/g, "\\'"));

escape sequence javascript

How can I pass variable to other function in this condition ,
I'm inserting textarea through javascript with single quotes,
but when it gets called myFunction(abc123), it looks like this,
the function suppose to be like this when it is called - myFunction('abc123')
so what should i do ?
myNum=123;
focusVar = "abc"+myNum;
$("#myDiv").append('<textarea onFocus="onFocusReportReply('+focusVar+')" onBlur="onBlurReportReply()" id="replyReportText'+data.activityId1+'">')
$("#myDiv").append('<textarea onFocus="onFocusReportReply(\''+focusVar+'\')" onBlur="onBlurReportReply()" id="replyReportText'+data.activityId1+'">')
Backslashes escape special characters, in this case string delimiters.
You can either use double quotes or escaped single quotes.
var foo = 'onFocus=myFunc("' + focusVar + '") moar';
or
var foo = 'onFocus=myFunc(\'' + focusVar + '\') moar';
To escape special characters, you need a leading backslash. Examples are
\t (tabulator)
\n (line feed)
\\ (backslash)
Enclose your string inside single quotes, like this:
myNum=123;
focusVar = "'abc"+myNum+"'";

Categories

Resources