HTML special characters does not replaced by Javascript - javascript

I'm trying to decode some specail characters in my string, before input it in HTML. But, for some reason, it didn't work.
For ex:
My input string is "ampere 13th\'."
In JS I'm replacing every special character with this function:
htmlEntities: function(str) {
return str.replace(/\\/g, "\").replace("'", "'").replace(".", ".").replace("%", "%").replace("\"",""");
},
But, when put it to HTML, it still looks like :
"ampere 13th\'."
I want to show my data with replaced special characters.
What I'm doing wrong?

There is a single backslash in your string which is not being recognized as '\' but instead its an escape sequence. Other characters are being replace perfectly. I have written the following function which alerts the output string accordingly.
function test() {
var str = "ampere 13th\'.";
alert(str.replace(/\\/g, "&#92").replace("'", "'").replace(".", ".").replace("%", "%").replace("\"", """));
}
And it alerts me
ampere 13th'.
which is correct except replacing the '\' character. if you want to replace the '\' you can further search on how to replace a backslash character in java script.
if I have my input string like this
var str = "ampere 13th\\'.";
with two backslashes then the replacement occurs perfectly and my function alerts me
ampere 13th&#92'.

Related

Replace ascii codes with strings in Javascript

I created a simple javascript function that receives a string and parses through it and updates other form fields. The function is called when I use a scanner to read a 2D barcode. My problem is that there are multiple fields separated with ascii code 29 which is the "group separator". I'm trying convert all the special characters to a readable string like "". I tried doing a replace like:
var BC = barcodestring.replace(String.fromCharCode(29), '');
Also, will the "replace" function replace just 1 or all of the occurrences?
This should work to replace the default replace function to it replaces all of that character.
barcodestring = barcodestring.replace(new RegExp(String.fromCharCode(29).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), "")

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

Escaping backslash in a string containing backslash

I have a string containing I\u2019m (with backslashes not escaped)
var myString = 'I\\u2019m'; // I\u2019m
But then I need a function that 'escape backslashes' that string, so the function I'm looking for would return I'm
backslashString(myString); // I'm
I've tried using eval:
function backslashString(input){
input = input.replace(/'/g, "\\'"); // Replace ' with \' that's going to mess up eval
return eval(`'${input}'`);
}
But is there a proper way of doing it? I'm looking for a function that escape backslashes a string containing I\u2019m to I'm and also handles if there's an extra backslash (A lost \ backslash)
EDIT:
I did not ask what I meant from the start. This not only applies to unicode characters, but applies to all backslash characters including \n
The backslashes aren’t the real problem here - the real problem is the difference between code and data.
\uXXXX is JavaScript syntax to write the Unicode codepoint of a character in a text literal. It gets replaced with the actual character, when the JavaScript parser interprets this code.
Now you have a variable that contains the value I\u2019m already - that is data. This does not get parsed as JavaScript, so it does mean the literal characters I\u2019m, and not I’m. eval can “fix” that, because the missing step of interpreting this as code is simply what eval does.
If you do not want to use eval (and thereby invite all the potential risks that entails, if the input data is not completely under your control), then you can parse those numeric values from the string using regular expressions, and then use String.formCharCode to create the actual Unicode character from the given code point:
var myString = 'I\\u2019m and I\\u2018m';
var myNewString = myString.replace(/\\u([0-9]+)/g, function(m, n) {
return String.fromCharCode(parseInt(n, 16)) }
);
console.log(myNewString)
/\\u([0-9]+)/g - regular expression to match this \uXXXX format (X=digits), g modifier to replace all matches instead of stopping after the first.
parseInt(n, 16) - to convert the hexadecimal value to a decimal first, because String.fromCharCode wants the latter.
decodeURIComponent(JSON.parse('"I\\u2019m"'));
OR for multiple
'I\\\u2019m'.split('\\').join().replace(/,/g,'');
'I\u2019m'.split('\\').join().replace(/,/g,'');
Looks like there's no other way other than eval (JSON.parse doesn't like new lines in strings)
NOTE: The function would return false if it has a trailing backslash
function backslashString(input){
input = input.replace(/`/g, '\\`'); // Escape quotes for input to eval
try{
return eval('`'+input+'`');
}catch(e){ // Will return false if input has errors in backslashing
return false;
}
}

Why this JavaScript RegExp results in dual answer?

Look at this simple HTML input tag:
<input type='text' id='phoneNumber' name='phoneNumber' class='inputBig textLeft'
data-validation='required regex'
data-validation-regex-pattern='^\\+\\d{2}\\.\\d{10}$'
value='+98.2188665544' />
<p id='log'></p>
Now imagine that we want to validate this field, using this function:
var log = $('#log');
function validateRegex(field) {
var pattern = field.attr('data-validation-regex-pattern');
log.append(pattern + '<br />');
if (pattern && pattern != '') {
var isValid = new RegExp(pattern).test(field.val().trim());
if (!isValid) {
log.append('not valid<br />');
}
else {
log.text('valid<br />');
}
}
}
validateRegex($('#phoneNumber'));
var isValid = new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val());
log.append(isValid.toString());
Now, if you look at the log, you see that this line returns false:
var isValid = new RegExp(pattern).test(field.val().trim());
However, this line of code returns true:
new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val().trim());
In other words, when the pattern of the RegExp object is passed to it as a string variable, it doesn't work. But when you pass a string literal, it works.
Why? What's wrong here?
To see it in action, look at this fiddle.
Escaping backslashes applies only to JavaScript, it isn't necessary for HTML. Therefore, the following attribute string:
data-validation-regex-pattern='^\+\d{2}\.\d{10}$'
Will work just fine:
Updated fiddle: http://jsfiddle.net/AndyE/GRL2m/6/
\\ is the method to write \ in a JavaScript String. The HTML data-attribute, written in JS would be \\\\, instead of \\.
Eg: <a data-x="\\">(HTML) is equivalent to '<a data-x="\\\\">' (JS).
To get your code work, replace double slashes (\\) in your HTML by a single slash.Fiddle: http://jsfiddle.net/GRL2m/5/
Extra information:
In HTML, HTML entities (eg ") are used to display special characters.
In JavaScript, escapes (eg \n, \x20, \u0009, ..) are used to display special characters.
In a RegExp, special RE characters have to be escaped by a slash (/\./). When the RegExp is constructed using a string, the slash has to be escaped, so that the slash also appear at the RegExp. "\." equals '.', while "\\." equals '\.'.

# symbol for strings in jQuery

if (confirm('<%=Ns1.Ns2.MyClass.GetResourceText("DeleteConfirmationMessage")%>')) { /* something to do...*/ }
I have a jQuery expression as above. But the return value of GetResourceText method is a very long string. So my page renders the function like below:
if (confirm('
Are you sure lablabla? If you delete this lablabla...
lablabla...
')) {
Because of this my jQuery functions do not work. Is there a symbol for jQuery like # that we use in C#?
Note: jQuery is not a special language, that would be javascript.
You will have to pass this string though an extra method that replaces all newlines with the string "\n". Take care when doing this from C#: you need the literal string "\n" so you will need escaping, either #"\n" or "\\n".
You also will need to watch out for quotes: a message like "call O'Brien" will fail with a javascript error. Replace that with "&apos;".
\. Just place it at the end of the line:
var str = "this \
is on more \
than one line \
and is valid.";
alert(str); // alerts "this is on more than one line and is valid."

Categories

Resources