store ":;',./<>?,./asdaA12 in javascript variable dynamicaly (Unexpected token error) - javascript

I am tying to store ":;',./<>?,./asdaA12 value in js variable which is in gsp page but it could'nt store it properly and gives me run-time error because of special symbol contain " and ' as string.
my snap code is :
var editGrp_billingCode_val ="${returnVal?.groupCommand?.billingCode?:billingCode?:billingCode}";
Here Billing code populate with : ":;',./<>?,./asdaA12 value which contain " or ' symbols so for that page gives me run-time js error
is there any one solution for converting this types of string into String variable and store into js variable. like toString method in java
Value ":;',./<>?,./asdaA12 is not fixed it will come dynamically while running the application so i have to convert it at run-time as stored in js variable

I've figured it out, just enclose your variable (symbols) in between the "forward slash" e.g
<script>
var x = /".'*:",/
alert(x)
// this should print ".'*:",
</script>

By escaping them:
<script>
var x = "\".'*:\","
alert(x)
// this should print ".'*:",
</script>
Short escaping list:
" = \" or ' = \'
\ = \\
New Line = \n
Tab = \t
more: w3schools - JavaScript Strings

Related

Why the .replace() and toUppercase() did not work in the second function? [duplicate]

I want to replace the smart quotes like ‘, ’, “ and ” to regular quotes. Also, I wanted to replace the ©, ® and ™. I used the following code. But it doesn't help.
Kindly help me to resolve this issue.
str.replace(/[“”]/g, '"');
str.replace(/[‘’]/g, "'");
Use:
str = str.replace(/[“”]/g, '"');
str = str.replace(/[‘’]/g, "'");
or to do it in one statement:
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
In JavaScript (as in many other languages) strings are immutable - string "replacement" methods actually just return the new string instead of modifying the string in place.
The MDN JavaScript reference entry for replace states:
Returns a new string with some or all matches of a pattern replaced by a replacement.
…
This method does not change the String object it is called on. It simply returns a new string.
replace return the resulting string
str = str.replace(/["']/, '');
The OP doesn't say why it isn't working, but there seems to be problems related to the encoding of the file. If I have an ANSI encoded file and I do:
var s = "“This is a test” ‘Another test’";
s = s.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
document.writeln(s);
I get:
"This is a test" "Another test"
I converted the encoding to UTF-8, fixed the smart quotes (which broke when I changed encoding), then converted back to ANSI and the problem went away.
Note that when I copied and pasted the double and single smart quotes off this page into my test document (ANSI encoded) and ran this code:
var s = "“This is a test” ‘Another test’";
for (var i = 0; i < s.length; i++) {
document.writeln(s.charAt(i) + '=' + s.charCodeAt(i));
}
I discovered that all the smart quotes showed up as ? = 63.
So, to the OP, determine where the smart quotes are originating and make sure they are the character codes you expect them to be. If they are not, consider changing the encoding of the source so they arrive as “ = 8220, ” = 8221, ‘ = 8216 and ’ = 8217. Use my loop to examine the source, if the smart quotes are showing up with any charCodeAt() values other than those I've listed, replace() will not work as written.
To replace all regular quotes with smart quotes, I am using a similar function. You must specify the CharCode as some different computers/browsers default settings may identify the plain characters differently ("",",',').
Using the CharCode with call the ASCII character, which will eliminate the room for error across different browsers, and operating systems. This is also helpful for bilingual use (accents, etc.).
To replace smart quotes with SINGLE QUOTES
function unSmartQuotify(n){
var name = n;
var apos = String.fromCharCode(39);
while (n.indexOf("'") > -1)
name = name.replace("'" , apos);
return name;
}
To find the other ASCII values you may need. Check here.

replace multiple words in string based on an array [duplicate]

I want to replace the smart quotes like ‘, ’, “ and ” to regular quotes. Also, I wanted to replace the ©, ® and ™. I used the following code. But it doesn't help.
Kindly help me to resolve this issue.
str.replace(/[“”]/g, '"');
str.replace(/[‘’]/g, "'");
Use:
str = str.replace(/[“”]/g, '"');
str = str.replace(/[‘’]/g, "'");
or to do it in one statement:
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
In JavaScript (as in many other languages) strings are immutable - string "replacement" methods actually just return the new string instead of modifying the string in place.
The MDN JavaScript reference entry for replace states:
Returns a new string with some or all matches of a pattern replaced by a replacement.
…
This method does not change the String object it is called on. It simply returns a new string.
replace return the resulting string
str = str.replace(/["']/, '');
The OP doesn't say why it isn't working, but there seems to be problems related to the encoding of the file. If I have an ANSI encoded file and I do:
var s = "“This is a test” ‘Another test’";
s = s.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
document.writeln(s);
I get:
"This is a test" "Another test"
I converted the encoding to UTF-8, fixed the smart quotes (which broke when I changed encoding), then converted back to ANSI and the problem went away.
Note that when I copied and pasted the double and single smart quotes off this page into my test document (ANSI encoded) and ran this code:
var s = "“This is a test” ‘Another test’";
for (var i = 0; i < s.length; i++) {
document.writeln(s.charAt(i) + '=' + s.charCodeAt(i));
}
I discovered that all the smart quotes showed up as ? = 63.
So, to the OP, determine where the smart quotes are originating and make sure they are the character codes you expect them to be. If they are not, consider changing the encoding of the source so they arrive as “ = 8220, ” = 8221, ‘ = 8216 and ’ = 8217. Use my loop to examine the source, if the smart quotes are showing up with any charCodeAt() values other than those I've listed, replace() will not work as written.
To replace all regular quotes with smart quotes, I am using a similar function. You must specify the CharCode as some different computers/browsers default settings may identify the plain characters differently ("",",',').
Using the CharCode with call the ASCII character, which will eliminate the room for error across different browsers, and operating systems. This is also helpful for bilingual use (accents, etc.).
To replace smart quotes with SINGLE QUOTES
function unSmartQuotify(n){
var name = n;
var apos = String.fromCharCode(39);
while (n.indexOf("'") > -1)
name = name.replace("'" , apos);
return name;
}
To find the other ASCII values you may need. Check here.

Break out from JavaScript variable

So, I have the following code:
<script type="text/javascript">
var name = prompt("What's your name?");
var greeting = "Hello " + name + " :D";
console.log(greeting);
</script>
I am trying to break out from name variable. For example: answering the question by
"alert(1);\\
In browser console, printing name variable shows the following:
Now, when trying to create a second variable with the same content it produces an error.
Why does "name" contain invalid syntax content? and is there any way to break out from the variable in this scenario?
When you input "alert(1);\\ in the prompt, the special characters are automatically escaped and the input is assigned to name, but when you are doing that via the console or a script, you have to escape the characters manually. Since you wrote the string using double-quotes, the correct way to do the assignment would be:
var test = "\"alert(1);\\\\";
When uing single-quotes, you wouldn't have to escape the double-quotes:
var test = '"alert(1);\\\\';
What I did here is escape the required characters by putting a \ before them. What you see when you try to view the value of name is the actual content without the escaping.
JavaScript believes that you are ending the string literal at the second quotation mark.
Two possible solutions:
Wrap with single quotes: test = '"alert(1)\\'
Escape the second quote: test = "\"alert//"

Assigning string value in <script> tag with "\n" is getting an error

I am trying to assign a string value to a javascript variable as below:
<script>
var iAmDone = 'asdasdaGRTPXqe1RWA8jikLwJSDc0lSNWCGA8NPioRhXlgxbQuTuxS6kkt3cA\nkDKp9/8zvA==';
</script>
This assignment is breaking the assignment from '\n' and thereby the value in iAmDone is not getting assigned. When I look into the console, it shows:
var iAmDone = 'asdasdaGRTPXqe1RWA8jikLwJSDc0lSNWCGA8NPioRhXlgxbQuTuxS6kkt3cA
kDKp9/8zvA=='; **X error**
What can I do to make the browser understand the \n is not a newline but part of a string?
** Just to add - The value is an encoded string and changing the same would be the last thing in my mind **
\n means new line, so string '12\n34' will be logged as:
'12
34'
To remedy this, you need to "escape" the string. For your specific case, you can add an additional \, IE '12\n34' -> '12\\n34'.
A more scaleable option is to use the JSON.stringify function:
const s = `12\n34`;
console.log('s: ', s);
const stringified = JSON.stringify(s);
console.log('stringified: ', stringified);
JSON.parse will convert the stringified result back to normal.

JSON.stringify / parse oddness with quote marks

I am running into an odd little problem with parsing some JSON which has quotes in it. I am using the native JSON.stringify and JSON.parse functions to do this. If I stringify an object which an object which has quote marks in it, they are escaped as one would expect. If I then parse this back into an object, it again works fine.
The problem is occurring where I stringify, then print the object to a page, then parse the resulting string. If I try to do this, the parse function fails as stringify has only put single slashes before each of the offending quote marks.
The reason I need to achieve this is I am working on an application that dynamically loads content stored in a database as JSON strings. The strings at some point need to be printed onto the page somewhere so that the javascript can find them and build the page based on their contents. I need some way of robustly passing the object into and out of strings which will not fail if a user inputs the wrong characters!
I can solve this for the moment by inserting extra slashes into the code with a replace call, but I was wondering if there is a better way to handle this?
I have put together a couple of jsfiddles to illustrate what I am trying to describe:
http://jsfiddle.net/qwUAJ/ (Stringify then parse back)
var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';
var string = JSON.stringify(ob);
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');
$('div').html(string);
http://jsfiddle.net/a3gBf/4/ (Stringify, then print, then parse back)
// Make an object
var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';
// Turn the object into a JSON string
var string = JSON.stringify(ob);
// Printing the string outputs
// {"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}
$('.stringified').html(string);
// Attempt to turn the printed string back into an object
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');
// This fails due to the single escaped quote marks.
Thank you for any help in advance!
This is a problem which arises from re-evaluating a String without first converting it back into a string literal, so the meaning changes if it is even still valid.
You need to consider what does '\"' as a literal actually mean? The answer is ", without the \. Why?
\" resolves to "
If you want to have \" as the result of the literal, you need to write '\\\"'
\\ resolves to \
\" resolves to "
So basically, the extra slashes are required to escape any characters with special meaning in string literals.
If you did var reOb = JSON.parse($('.stringified').html()); it would work fine as is.
Consider further
str = '\\\"\\\''; // \"\'
str = '\"\''; // "'
str = '"''; // SyntaxError: Unexpected token ILLEGAL
As far as I'm aware, JavaScript offers no native implementation to convert strings as desired, so the easiest method I know of is using a replace
function toLiteral(str) {
var dict = {'\b': 'b', '\t': 't', '\n': 'n', '\v': 'v', '\f': 'f', '\r': 'r'};
return str.replace(/([\\'"\b\t\n\v\f\r])/g, function ($0, $1) {
return '\\' + (dict[$1] || $1);
});
}
toLiteral('foo\\bar'); // "foo\\bar"
If you generate JS with PHP code you should escape the quotes in your JSON string:
//PHP code generating js code
echo "var myJSONString = \"". str_replace("\"","\\\"",$mySqlJSON)."\";";

Categories

Resources