Change the backslashes in a URI to forward-slashes with javascript - javascript

I'm writing an app that will let the user import pictures. I'm running windows, so the file path that is returned when the user selects a picture has backslashes, which is what I believe to be causing javascript to fail when I pass the path to my import method.
I get the file path with a simple html file input and use a submit button with an onclick call to my javascript:
<input type="file" id="photo-to-import" />
<input type="button" value="Submit" onclick="console.log($('#photo-to-import').val().replace('/\\/g','/'))"/>
console.log is normally where the function call would go, I've changed it for debugging. If I hard code in a file path to a picture and go through and manually change the slashes, it imports the picture, for example, I'll copy/paste a path:
C:\Users\Name\Desktop\desktop app\images\imageName.png
into the function and change the slashes I end up with:
<input type="button" value="Submit" onclick="onPhotoURISuccess('C:/Users/Name/Desktop/desktop app/images/imageName.png')"/>
and this works great. I have tried
.replace('\\\\', '/')
.replace('\\', '/')
...
and always get the exact same output, the string is unchanged every time.

Change replace('/\\/g','/') to replace(/\\/g,'/'), with the quotes you will be attempting to replace literal matches of the string '/\\/g' instead of using a regular expression literal.
For example, 'foo /\\/g bar'.replace('/\\/g','/') will give you 'foo / bar', and 'C:\\Users\\Name\\Desktop\\desktop app\\images\\imageName.png'.replace(/\\/g,'/') will give you 'C:\Users\Name\Desktop\desktop app\images\imageName.png'.

Related

"Literally" insert string into HTML input

I want to insert a string "literally" into an HTML input field using jQuery.
The problem is that the string contains escaped characters and character codes, and all of those need to still be there when the string is inserted.
My problem seems to be with escaped characters (thanks for the comments that pointed that out). I can't figure out how I can insert the string without the escaped characters and codes being translated.
The literal strings come from a file data.txt. To clarify, this is just an exemplary string that is used to demonstrate that there can be escaped quotes and character codes etc. in the strings.
TEST\"/**\x3e
They are loaded (in node.js) from the file into an array of strings.
Wrapper code (Node.js) visits the page using the Chrome dev tools.
Here, for each string a script is prepared that is injected and executed on the page.
Therefore the inputString is inserted into the script, before it is injected.
So here is my problem with string escaping. I have the strings in literal format as data and I currently inject them as dynamically generated JavaScript code which is where escaping problems occur.
Injected Code
// this was (currently incorrectly) injected into the page before
// from the array of input strings that was loaded from data
let insertString = "TEST\"/**\x3e"; // <-
let form = $("form").first();
let inputs = form.find(":input").not(":input[type=submit]");
let input = inputs.first();
input.focus().val(insertString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Exemplary form code on the page -->
<form action="post" method="post">
<label for="name">Name: </label>
<input id="name" type="text" name="input">
<input type="submit" value="Submit">
</form>
What we got
What I want
The string is not inserted as is.
For example the character code \x3e is translated to >.
Also the escaped \" is translated to ".
It needs to be inserted just as it would be when copying and pasting from the data file.
Thoughts on a potential (manual) solution
So one potential solution is to rework the data.txt file and escape the strings correctly. So the first line might be TEST\\\"/**\\x3e, as #Jamiec and #Barmar have proposed.
// injected before
let insertString = "TEST\\\"/**\\x3e"; // <- manually escaped
let form = $("form").first();
let inputs = form.find(":input").not(":input[type=submit]");
let input = inputs.first();
input.focus().val(insertString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Exemplary form code on the page -->
<form action="post" method="post">
<label for="name">Name: </label>
<input id="name" type="text" name="input">
<input type="submit" value="Submit">
</form>
The string will then be inserted as intended, but the solution is still not satisfying, because it would be better for me to not touch the input data.
It would be best to have the input strings in the data.txt file exactly as they will look when they are inserted into the page.
This would require and additional step between loading the input data and inserting each string into the script (that is then injected into the page). Potentially this preprocessing can be done with regexp replacements.
You need to escape all the backslashes and quotes in the string. You can do this using a regular expression.
function escape_string(string) {
return string.replace(/[\\"']/g, "\\$&");
}
console.log('let str = "' + escape_string(prompt("Type a string")) + '";');
This has nothing to do with encoding, nor input fields - it is simply string escapes - so can be demonstrated using the console (or any other way of displaying a string).
In order to see the literal escape character \ in a string you must escape the escape character with \\ - see below:
var text1 = "TEST\"/**\x3e";
console.log(text1)
var text2 = "TEST\\\"/**\\x3e";
console.log(text2)
As you can see the first output is your exact problem, where as the second escapes the escape character so you get what you expect in the output.

Spotfire : How to modify an URL in an input field (after being entered by the user)

I'm trying to import a file in spotfire depending on the path entered by the user.
I'm using a data function (R script). As you know, in R all "\" are not recognized and consequently must be replaced by : "/".
If the user is entered in the input filed the path with "/" as delimiter : the file is well importing.
I would like to adapt my R script in order to permit users to paste his original path (with "\") and then to replace with "/".
I don't understand well why it seem like we can't use R function like paste on the variable containing the input field (see the following pictures).
Note that path is the name of the document proporty (the input filed) and the script has been tested with and without the as.character line.
Can someone help me?
Any help would be appreciated :)
can't you use simple regex to replace '\' with '/'?
Something like
sub('\', '/', str)
(You probably need to escape this)

Concatenate Two Strings in HTML where one string has a Hyperlink in between

I have two strings in html. The two strings are "Forgotten your password?" and "Please" 'HPERLINK' "to change your password".
Now I have a messageBundle file which is a file to store constants. This file is used to translate the constants in other languages.
Now I have stored these strings in my constant file as:
Forgot_Pass="Forgotten your password?Please"
Forgot_password_continue="to change your password"
Then in html I am using this constants file to create a complete sentence on my UI as "Forgotten your password? Please click_here to change your password".
Here 'click_here' is the hyperlink.
Is there anyway I can store this error message in a single string in my MessageBundle file so that concatenation of these 2 strings can be avoided?
This seems to be the solution for me:
Forgot_Pass="Forgotten your password?Please Click here to change your password"
If I am wrong, please let me know.
You can do this by making use of a pre-defined pattern for variables (eg: ##1##, ##2## etc.,) that can be replaced with the corresponding values at the time of translation.
For example: You final (single) string could be as follows -
Forgot_Pass_Change="Forgotten your password? Please ##1## to change
your password"
where ##1## will need to be replaced with the <a href="http://your.link.path" >click_here</a> at the time of translation.
I understand that this means having to change the way the translation calls happen. Assuming that your current translation function is something like getTranslatedString(<translate_string_name>), you could override it to something like the one shown below:
getTranslatedString('Forgot_Pass_Change', [<variable_1>, <variable_2> ...]);
i.e
getTranslatedString('Forgot_Pass_Change', ['click_here_hyperlink']);
In your example you have only 1 variable string. However, there will be cases where you will need to replace more than 1 variable at a time (denoted by ##2##, ##3## and so on, in your template string). Hence the array implementation as the second parameter.

Is my "email me" button code wrong?

my code keeps saying this "Unterminated regular expression literal. (line 5, file "Code")" pls help
here is what I have:
<FORM>
</INPUT TYPE="button"
VALUE="click here to add a game"
onClick="parent.location='mailto:1637206#student.ucps.k12.nc.us?subject=I would like to add a game to the website'">
</FORM>
You have your opening tag starting with a forward slash and no closing tag.
<FORM>
<INPUT TYPE="button"
VALUE="click here to add a game"
onClick="parent.location='mailto:1637206#student.ucps.k12.nc.us?subject=I would like to add a game to the website'"/>
</FORM>
Start with <Input then terminate the tag with />
As Wobbles already answered, the syntax of your INPUT element is invalid.
However, 'mailto:1637206#student.ucps.k12.nc.us?subject=I would like to add a game to the website' is also invalid because you have spaces in the value for the parameter subject: It would be parsed as subject=I followed by gibberish which the parser wouldn't understand; You need to encode special characters for it to be parsed reliably:
Make sure you encode all special characters. Common character encodings are below, or you can use Eric Meyer’s URL encoder tool. If you would rather learn what all the character encodings are, you can use this resource.
Common character encodings
space = %20 or + (either one works)
line break / carriage return = %0D%0A
question mark = %3F
/ (forward slash) = %2F
: (colon) = %3A
You do not need to encode commas (,) or periods (.).

URL Encoding in JS for meaningful URLs and Rails Page Caching

I'm running a Rails Application which gets a lot of traffic at the moment so I started using Page Caching to increase the performance. So far everything works like a charm. But when I tried to also cache search results I run into a strange problem.
My Approach:
Use meaningful URLs for searching and pagination (/search?query=term&page=3 becomes /search/term/3)
Use Javascript to submit the form - if JS is disabled it falls back to the old form (which also works with my routes, but without caching)
My Code:
// Javascript
function set_search_action() {
window.location = '/search/' + escape(document.getElementById('query').value);
return false;
}
// HTML
<form action="/search" id="search_form" method="get" onSubmit="return set_search_action();">
<input id="query" name="query" title="Search" type="text" />
<input class="submit" name="commit" type="submit" value="Search" />
</form>
The Problem
Everything works for single words like "term". But when I search for "term1 term2" the form is submitted to /search/term1 term2/ or /search/term1 term2/1 . It should be submitted to /search/term1+term2 That's what the JS escape function should do I think.
So far it works also with spaces in development mode. But I guess it will become a problem in production mode with caching enabled (URLs shouldn't contain any whitespaces).
Any ideas on what I did wrong? Thanks!
It should be submitted to /search/term1+term2
Nope. Plus symbols only represent spaces in application/x-www-form-urlencoded content, such as when the query-string part of the URL is used to submit a form. In the path-part of a URL, + simply means plus; space should be encoded to %20 instead.
That's what the JS escape function should do I think.
Yes it does, and that's the problem. escape encodes spaces to +, which is only suitable for form submissions; used in a path, you will get an unexpected and unwanted plus sign. It also mangles non-ASCII characters into an arbitrary format specific to the escape function that no URL-decoder will be able to read.
As Tomalak said, escape()/unescape() is almost always the wrong thing, and in general should not be used. encodeURIComponent() is usually what you really want, and will produce %20 for spaces, which is safe as it is equally valid in the path part or the query string.
Never use escape()! It's broken and highly dis-recommended for what you do. Use encodeURIComponent() instead.
To have + instead of %20, append a .replace(/%20/g, "+").

Categories

Resources