# symbol for strings in jQuery - javascript

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

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

Split string str.split("\\") using javascript

i have a string "demo1\demo2".
var str="demo1\demo2";
console.log(str.split("\\")[1])); \\gives undefined
console.log(str.split("\")[1])); \\gives undefined
gives undefined.
i need to demo2 in console.log
You're escaping the d after the \ in str. You need to escape the \ in str:
const str = 'demo1\\demo2';
console.log(str.split('\\'));
Just like #SimpleJ already answered, you need to escape your backslash so that it is not considered to be escaping the next character itself. As proof, when you don't escape your backslash with another backslash, here is how your string gets outputted (in case you haven't checked this yourself already):
> console.log('demo1\demo2')
demo1
undefined
> console.log('demo1\\demo2')
demo1\demo2
undefined
> console.log("demo1\demo2")
demo1
undefined
> console.log("demo1\\demo2") // same goes for double quoted strings
demo1\demo2
undefined
So this is the way to go:
"demo1\\demo2".split("\\")
If the items inside need escaping, you could run it through something like this first.
If you just need 'demo2' and you know what characters it has, you could something like:
console.log(str.match(/[^a-z0-9A-Z]([a-z0-9A-Z]*)$/)[1]);
or similar.

How to use symbols as parameters for javascript functions

In my header i'm using the function
function changefinal(text)
{
if (text == ".")
{
final = final + ".";
}
}
But when I call the function as changefinal(.) my final variable does not change. Not sure what I'm doing wrong here. Am I defining the parameter wrong?
You have to quote your symbols. In JavaScript, a double quotation character has the same effect as a single quote-character. When you're quoting something in JavaScript, the contents inside the quote is interpreted literally, and the created object is a string.
changefinal(".");
changefinal('.');
If you ever have to use a literal quote inside the same quote (example" inside "..."), a prefix the inner quote by a backslash, to escape the quote:
var string = 'I\'m Rob W.';
alert(string); //shows: I'm Rob W.
var attempt = 'I'm Rob W.'; //Notice: No backslash
^ Syntax error
Well
changefinal(.);
is a syntax error. You probably want
changefinal(".");

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 '\.'.

replaceAll in javascript and dollar sign

I have a string with 3 dollar signs e.g. $$$Test123. I would like to display this string in a div.
The problem is that when I use replace I get $$Test123 - 2 dollar signs instead of 3.
example:
var sHtml="<_content_>";
var s="$$$Test";
sHtml= sHtml.replace("<_content_>", s);
Now the result of sHtml is $$Test;
Any idea how can it be solved?
javascript does not have a default replace all function. You can write your own like this
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'),with_this);
}
$ has a special meaning when included in a string for the second argument of a call to replace(). Normally, you would use it to refer to matched expressions within the original string. For example:
"foo foooo".replace(/fo+/g, "$&bar");
//-> "foobar foooobar"
In the example above, $& refers back to the entire match, which is foo in the first word and foooo in the second.
Your problem stems from the special meaning of $. In order to use a literal $ in the match, you must chain two together so that the first escapes the second. To have 3 literal $ symbols, you must chain 6 together, like so:
var sHtml="<_content_>";
var s="$$$$$$Test";
sHtml= sHtml.replace("<_content_>", s);
//-> "$$$Test"
Quotes are your friend
var sHtml="<_content_>"
var s="$$$Test";
sHtml= sHtml.replace("<_content_>", s);
Try this replaceAll function:
http://www.dumpsite.com/replaceAll.php
It performs a replace all using the javascript replace function via a regular expression for speed, and at the same time eliminates the side effects that occur when regular expression special characters are inadvertently present in either the search or replace string.
Using this function you do not have to worry about escaping special characters. All special characters are pre escaped before the replaceAll is preformed.
This function will produce the output you are expecting.
Try it out and provide your feeback.

Categories

Resources