How to escape characters in a string - javascript

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

Related

How to fix 'missing) after argument list' error in Javascript

Why is this giving me this error?
<script>
function loadImg() {
var imageChosen = document.getElementById('imageChosen').value.replace("C:\fakepath\","");
alert(imageChosen);
document.getElementById('image').src = imageChosen;
}
</script>
I expect the image with id "image" to show the chosen image.
The value in your call to replace() is not escaped properly.
The value should instead be:
"C:\\fakepath\\",""
Read more about escaping strings here
The problem is due to the escape string character \ (backslash)
When using strings in Javascript we may escape some character in the string. For example a break line (\n) or even a "(double quotes) when declaring the string or even an backslash \ need a escape.
Examples:
x = "my \\" // Will output as the same as "my \"
z = "my \"quotes\" // Will output as 'my "quotes" '

How to replace "\" with "\\" from a string using Javascript?

I tried mystring.replace(/\\/g,"\\") but that didn't work.
Can someone advise me how to do this replacement?
Example: String = "C:\Users\Test\FileName"
When I replace \ with \\, I need to see a result as follows:
C:\\Users\\Test\\FileName
Inside string \-backslash is used to escape the following character. In the string, "C:\Users\Test\FileName" also backslash is used as escape sequence and actual string is "C:UsersTestFileName"
var str = "C:\Users\Test\FileName";
console.log(str);
To make this correct, the backslashes in the string should already escaped.
var str = "C:\\Users\\Test\\FileName";
var str = "C:\\Users\\Test\\FileName";
console.log(str);
The regex can now be used to double the backslashes
str.replace(/\\/g, '\\\\');
var str = "C:\\Users\\Test\\FileName";
console.log(str);
console.log(str.replace(/\\/g, '\\\\'));
Try this, use raw string,String.raw() method is a tag function of template literals
String.raw`\"`.replace(/\"/g, '\\"');
or,if first one isn't work,try this :) hope this will be helped to you
String.raw\".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+"'";

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>';

Javascript Replace Regex

Ok, I'm actually trying to replace text.
Basically, I am needing to replace all instances of this: | with a blank string ''
However, this isn't working:
langName = langName.replace(/|/g, '');
Also, would be best if I could also replace all of these instances within the string, with a '' also:
" double quote
' single quote
/ back slash
\ forward slash
And any other html entity characters. Arrggg.
Can someone please help me here? Perhaps it can be turned into a String.prototype function so I can use it more than once?
Thanks :)
You need to escape | with \ like:
langName = langName.replace(/\|/g, '');
Test Case:
var langName = 'this| is | some string';
langName = langName.replace(/\|/g, '');
alert(langName);
Output:
this is some string
The reason why you need to escape | is that it is special regex character.
Alternatively, you could also use split and join like this:
langName = langName.split('|').join('');

Categories

Resources