Replacing backslashes in Javascript with escaped backslahes - javascript

Our application needs to process a file path (ie. snip off the last element) which we get in non escaped form c:\blah\di\blah. Unfortunately the backslashes are not escaped, like c:\\blah\\di\\blah, which means that javascript does not really recognise the backslahes; calling a function like indexOf(\\) will return -1.
I have seen countless questions on stackOverflow but I am at a loss on how to proceed.
There is no way we can change the data we get because it is from another framework (extJS),
Is there some way of replacing the single backslashes with \\ ? Then we could process it properly.
I tried :
str.replace(/\/, "\\\\");
str.replace(/\/g, "\\\\"); mentioned here.
str.replace(String.fromCharCode(92),String.fromCharCode(92,92)); mentioned here
str.replace("\\", "\\\\");
escape() function mentioned here. This gives me c%3A%08lahdi%08lah
In the same question this looked promising: var justTheName = str.split(String.fromCharCode(92)).pop(); But also does not work for me.
I have a fiddle with this code :
var str = 'c:\blah\di\blah'
str = str.replace(/\\/, "\\\\");
alert('' + str)

Related

Use jQuery to Auto Escape characters from a var

First, I'm not sure I've titled my question properly. Please feel free to correct me if needed.
My Issue:
I've created a variable, in jQuery called var siteTitle. This variable is available for other .js files to use and then get passed back to the .html page.
It all works great and there are no issues except when the var siteTitle will contain certain characters that need to be escaped. (quote, single quote, and ampersand to be specific)
What I would like to do is to use a bit of jQuery that would search a particular dom element and see if it is using any of those characters and then automatically escape them.
I've searched for some similar functions and can not seem to find exactly what I need ... the closet idea I have seen is something like this. Its not exactly what I need but it is something like what I am looking for.
pathto: function(path, file) {
var rtrim = function(str, list) {
var charlist = !list ? 's\xA0': (list + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
var re = new RegExp('[' + charlist + ']+$', 'g');
return (str + '').replace(re, '');
};
So, I am trying to write a function that will automatically convert those characters to be escaped or their html equivalent.
So, if the var siteTitle is used in a dom element like this:
<h1 class="titleText">' + siteTitle + '</h1>
I need to be able to make sure that any characters get escaped in that element.
Here is a jsFiddle that shows exactly what I am trying to do ...
https://jsfiddle.net/bbyrdhouse/5jb2fdsr/1/
Any help is greatly appreciated.
Since you're using jquery, use the .text() function to set the value into your HTML. It'll escape it appropriately.
var siteTitle = 'My Site "Title"';
$my('.titleText').text(siteTitle);
Also, in your fiddle, the siteTitle variable is not what you think it is, because the 2nd quotation closes that value since it's not yet escaped. I wrapped it in single quotes in my example.
Updated fiddle

Javascript replacing double backslashed with single backslash

I have been browsing lots of solutions, but somewhy haven't got anything to work.
I need to replace following string: "i:0#.w|dev\\tauri;" with "i:0#.w|dev\tauri;"
I have tried following JS codes to replace:
s.replace(/\\\\/g, "\\$1");
s.replace(/\\\\/g, "\\");
But have had no result. Yet following replaced my \\ with "
s.replace(/\\/g, "\"");
To be honset, then I am really confused behind this logic, it seems like there should be used \\\\ for double backshashed yet it seems to work with just \\ for two backshashes..
I need to do this for comparing if current Sharepoint user (i:0#.w|dev\tauri) is on the list.
Update:
Okay, after I used console.log();, I discovered something interesting.
Incode: var CurrentUser = "i:0#.w|dev\tauri"; and console.log(): i:0#.w|dev auri...
C# code is following:
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
return theUser.LoginName;
JavaScript strings need to be escaped so if you are getting a string literal with two back slashes, JavaScript interprets it as just one. In your string you are using to compare, you have \t, which is a tab character, when what you probably want is \\t. My guess is that wherever you are getting the current SharePoint user from, it is being properly escaped, but your compare list isn't.
Edit:
Or maybe the other way around. If you're using .NET 4+ JavaScriptStringEncode might be helpful. If you're still having problems it might help to show us how you are doing the comparison.

Remove new line in javascript code in string

I have a string with a line-break in the source code of a javascript file, as in:
var str = 'new
line';
Now I want to delete that line-break in the code. I couldn't find anything on this, I kept getting stuff about \n and \r.
Thanks in advance!
EDIT (2021)
This question was asked a long, long time ago, and it's still being viewed relatively often, so let me elaborate on what I was trying to do and why this question is inherently flawed.
What I was trying to accomplish is simply to use syntax like the above (i.e. multi-line strings) and how I could accomplish that, as the above raises a SyntaxError.
However, the code above is just invalid JS. You cannot use code to fix a syntax error, you just can't make syntax errors in valid usable code.
The above can now be accomplished if we use backticks instead of single quotes to turn the string into a template literal:
var str = `new
line`;
is totaly valid and would be identical to
var str = 'new\n line';
As far as removing the newlines goes, I think the answers below address that issue adequately.
If you do not know in advance whether the "new line" is \r or \n (in any combination), easiest is to remove both of them:
str = str.replace(/[\n\r]/g, '');
It does what you ask; you end up with newline. If you want to replace the new line characters with a single space, use
str = str.replace(/[\n\r]+/g, ' ');
str = str.replace(/\n|\r/g,'');
Replaces all instances of \n or \r in a string with an empty string.

str replace all in Javascript

I am trying to some some urls throught javascript where some replacement of urls needs to be done. I have a textarea with some URLs example given below:
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=1
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=2
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=3
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=3
Now what i am trying to do is replacing http://mywebsite.com/preview.aspx?mode=desktop&url= with spaces.
I have tried using str.replace() but it is replacing only first occurence of that url.
I have also tried with Global variable g the query i have used is
str_replace(\http://mywebsite.com/preview.aspx?mode=desktop&url=/g,'');
But its not working So can anyone tell me how i can do that ?
I want the output of the textarea like:
http://mywebsite.com/post.aspx?id=44&content=1
http://mywebsite.com/post.aspx?id=44&content=2
http://mywebsite.com/post.aspx?id=44&content=3
http://mywebsite.com/post.aspx?id=44&content=4
I believe that your biggest issue is that your regex syntax is incorrect. Try this:
Imagine that var s is equal the the value of your textarea.
s.replace(/http\:\/\/mywebsite\.com\/preview.aspx\?mode\=desktop\&url\=/g, '');
The issue you were having was improper delimiters and unescaped reserved symbols.
Though Javascript has some of its own regex idiosyncrasies, the issues here were related to basic regex, you might find these resources useful:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
http://regexpal.com
try this.
var string = document.getElementById('textareaidhere');
string.replace(/http:\/\/mywebsite\.com\/preview\.aspxmode=desktop&url=/g, '');
JSFiddle here

Parsing Phrases with a Pipe Character Using JavaScript

I've been working on my Safari extension for saving content to Instapaper and have been working on enhancing my title parsing for bookmarks. For example, an article that I recently saved has a tag that looks like this:
Report: Bing Users Disproportionately Affected By Malware Redirects | TechCrunch
I want to use the JavaScript in my Safari extension to remove all of the text after the pipe character so that I can make the final bookmark look neater once it is saved to Instapaper.
I've attempted the title parsing successfully in a couple of similar cases using blocks of code that look like this:
if(safari.application.activeBrowserWindow.activeTab.title.search(' - ') != -1) {
console.log(safari.application.activeBrowserWindow.activeTab.title);
console.log(safari.application.activeBrowserWindow.activeTab.title.search(' - '));
var parsedTitle = safari.application.activeBrowserWindow.activeTab.title.substring(0, safari.application.activeBrowserWindow.activeTab.title.search(' - '));
console.log(parsedTitle);
};
I started getting thrown for a loop once I tried doing this same thing with the pipe character; however, since JavaScript uses it as a special character. I've tried several bits of code to try and solve this problem. The most recent looks like this (attempting to use regular expressions and escape the pipe character):
if(safari.application.activeBrowserWindow.activeTab.title.search('/\|') != -1) {
console.log(safari.application.activeBrowserWindow.activeTab.title);
console.log(safari.application.activeBrowserWindow.activeTab.title.search('/\|'));
var parsedTitle = safari.application.activeBrowserWindow.activeTab.title.substring(0, safari.application.activeBrowserWindow.activeTab.title.search('/\|'));
console.log(parsedTitle);
};
If anybody could give me a tip that works for this, your help would be greatly appreciated!
Your regex is malformed. It should be:
safari.application.activeBrowserWindow.activeTab.title.search(/\|/)
Note the lack of quotes; I'm using a regex literal here. Also, regex literals need to be bound by /.
Instead of searching and then replacing, you can simply do a replace with the following regex:
str = str.replace(/\|.*$/, "");
This will remove everything after the | character if it exists.

Categories