简体   繁体   中英

Escape characters in JavaScript?

I am creating a file name like this

var name = $('#top-line').val();
var fname = random+'-'+name+'-something';

Here fname is file name. I don't know what the user might enter in #top-line, how can I escape the characters to be sure about safety. I tried it with a $top line = somethin "else" and things got messed up.

From the comment I read I understand that

escape("Need tips? Visit W3Schools!") will produce
Need%20tips%3F%20Visit%20W3Schools%21 

My doubt is will the file get saved as

Need%20tips%3F%20Visit%20W3Schools%21

What if someone writes escape(/Need tips? Visit W3Schools!")

EDIT on server I am saving files like

$name = uniqid('somevalue',true);
$file = 'usermemes/' . $name . '.jpeg';

On user computer they have the name that user provides.

You want to do this on the server . Here's why: even if your JavaScript is minified, remember that (theoretically) anyone can view and modify your script. You could write a great routine that checks for bad characters, makes sure the user isn't doing anything "injecty", and turns the input into a good filename for your server's OS, but if someone was really motivated, they could download a local copy of your page, edit the script, and fire off as many malicious requests to your server as they want.

It's reasonable to do some basic escaping on the client side (such as encodeUri - see this answer for details), but you'll want to do the real work on your server. Don't just take the user input, put it into a filename string, and save on the server. It can be as simple as a set of str_replace calls or a regex that checks for allowable characters. You just want to make sure you do it where the user can't see.

Edit : If you're just using the user-entered name locally, I'd go with encodeURIComponent and also remove single and double quotes with regex as Prabhu suggested. (But why not just have the file saved on the server with a unique name, and then have the user download that?

Initiate your "name" variable with empty string

var name= "";
name="Need tips? Visit W3Schools!";

and javascript will take "everything" as a string no mater it is a escape or what. even

var name= "";
name="\Need tips? Visit W3Schools!\";

or

var name= "";
name="Need\\ tips? Vis\\it W3\\School\\s!";

only thing is you need to take care of double quotes so it can be removed. so totally like this.

var name= "";
var name = $('#top-line').val();
name.replace(/['"]+/g, '');

or write a logic by using this to alert user not to enter double quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM