Jquery problems with some chars in strings - javascript

I'm having troubles with some string chars like 'c++', when trying manipulating that i receive an error: uncaught exception: Syntax error, unrecognized expression: +
Is there some way of declaring strings or somenthing more that can be usefull to this case?
In this case i pass var k = 'c++' to a function which prints that var in this way:
$('#wrapper').html('<span>'+k+'</span>');

Are you eval'ing the above code? As it stands what you have there works fine if it's just included in a page with var k = "c++".
If you are going to eval the string, then you should surround 'k' with quotes and also escape any quotes that might be in it.

That code looks fine. Runs with no problem here
That is not the line of code causing the error

Related

Javascript error: Invalid regular expression flags

So I have an error in my code that's saying Invalid regular expression flags. The line at fault is this one: ctx.drawImage(/Users/aUser/Desktop/NightSquare.png, 200, 200);, but aUser is replaced with my actual name (changed for privacy). I'm running on a mac and I think I know what the problem is (I didn't include MacIntosh HD), but I'm not sure. How do I fix this?
Additional notes: The /Users/ part of the code is highlighted in red in my text editor (the same color as a string).
Any thing in between / & / is treated as a regular expression in Javascript. There are 2 ways of creating regular expressions in JavaScript.
var myRegEx = new RegExp("pattern") ;
var myRegEx = /pattern/ ;
So using /Users/aUser/Desktop/NightSquare.png is actually leading to your code being interpreted as some regular expression creation which you do not intend.
Just make it a string literal( using "" or '') and it will be fine.
In case aUser is a variable ,use the following string concatenation-
"/Users/"+aUser+"/Desktop/NightSquare.png"
Strings need to be in quotes:
ctx.drawImage("/Users/aUser/Desktop/NightSquare.png", 200, 200);

Trying to escape a string to use as a jQuery selector

I have the following code, which I stole from another SO question,
$('#'+'^`test'.replace(/[!"#$%&'()*+,.\/:;<=>?#[\\\]^`{|}~]/g, "\\\\$&"))
which produces the following error.
Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)
I just have some IDs with crazy characters, like ^ and `, that I need jQuery to not choke on. I don't get why that error is happening, because if I manually add the slashes into the string like,
$('#'+'\\^\\`test')
then it works fine. What's wrong with the regex method?
I just have some IDs with crazy characters, like ^ and `, that I need jQuery to not choke on.
By far the simplest way to address that is with an attribute selector:
$('[id="' + theId + '"]').doSomething();
As long as theId doesn't contain backslashes or double quotes, no need for further escaping.
Another work around is to use the vanilla getElementById, which doesn't parse the selector. That way you still have the efficiency of selecting by id:
let res = $(document.getElementById('^`test'));
How about using this?
const $ID = function(selector){
return $('[id="' + selector.match(/#?(\S+)/)[1] + '"]')
}
Then you can use it just like jquery
$ID('#^`div')
You need 2 times the escape . Becouse first the replace/regex need the escape to write a escape. The next escape is need from jquery by $().
More clear syntax as the postet regex is:
"#^bla`".replace('^','\\\^').replace('`','\\\`');
will replace "#^bla`" to "#\\^bla\\`".
Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)
If you want to use your regex you must also escape [ ] with \[ and \].
"+".replace(/[!"#$%&'()*+,.'()*+,.\/:;<=>?#\[\\\]^`{|}~]/g, "yes")

JSON.parse throws errors while eval doesn't on the same strings. Why?

suppose I have something like
var a = '["\t"]'
If I do
eval('var result = ' + a)
Everything works fine. But if I do
var result = JSON.parse(a)
It throws error: Unexpected token.
Same happens with \b, \f: works with eval, while fails with JSON.parse. Why? Shouldn't the parser behave in the same way when encounters "\t"?
On the other hand, both eval and JSON.parse fail with a \n (as expected), but they also both fail with a \r. Why is this?
I'm a little bit confused with all this so could anybody explain what is going on? If possible with details: how is the parser behaving in the two cases?
You have to escape \ in the JavaScript string, so you'd end up with
var a = '["\\t"]'
For details, please refer to "http://json.org/"
Well that's because it's not valid JSON.
Don't try to write JSON yourself. Instead, use JSON.stringify to properly encode your data.
var json = JSON.stringify(["\t"]);
JSON.parse(json);
//=> ["\t"]

Regex: Replace Parentheses in JavaScript code with Regex

Need to remove spaces, single quotes, and parens from a string displayed in as an <li>
This works great for the first two:
var foo = li.replace(/\s|\'+/g, "");
I assumed all I needed to do was add another few ORs to this, escaping the ( or ) symbols to search for them:
var foo = li.replace(/\s|\'+/g|\(|\), "");
Compiler no likey:
Uncaught SyntaxError: Unexpected token ILLEGAL
It appears the the that the open and closing paren are getting evaluated anyway - even with the escape symbols. What am I doing wrong here? Thanks!
You don't have the right syntax for regex literals. They're written as
/pattern/flags
And what you seem to want isn't a bunch of OR but a character class.
Use
var foo = li.replace(/[\s'()]+/g, "");

String syntax error using javascript's replace function

I want to pass an email address as a query string and as such I encode it just before sending it with this line of code:
var encoded = encodeURIComponent(email).replace('.' '%2E');
Apparently the period shouldn't matter but I keep getting "can't find module 'com' " if i run it that way (I'm coding on node and using express and using a res.render() call)
Don't really understand why in my case periods are causing issues but either way this is the exact error I get:
var encoded = encodeURIComponent(email).replace('.' '%2E');
^^^^^
SyntaxError: Unexpected string
Don't really understand why in my case periods are causing issues
It's not the presence of a period. It's the lack of a comma.
var encoded = encodeURIComponent(email).replace('.', '%2E');
// ^ this here

Categories