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+"'";
Related
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)
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
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
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>';
Say I have a string value a\bc keeps in a variable, how can I turn it into a string in code like "a\\bc"? The string may contains tabs, slashes, new lines, etc.
I know there's a build-in JSON.stringify method in some browsers and there's a JSON2 lib but I just want to have a minimum piece of code can do the job only for string.
Sounds like premature optimization. Unless you have a problem with performance, I'd go with JSON.stringify, no extra code to write, no need to figure out how to encode it.
None of the answers here are good enough, since they don't encode all the possible things like \n, \r, \t or quotes
Here's a blatant copy of the code from json.org that does what you need. http://jsfiddle.net/mendesjuan/rFCwF/
function quote(string) {
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
}
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
If you just want to escape slashes and add quotes:
str = ['"', str.replace(/\\/g, '\\\\'), '"'].join('');
If you need a safe method to "escape" your strings, try this:
escape(str).replace(/%/g, '\\x')
It uses the internal escape function, then, converts the %-url escape format to -string escape format.