How to convert string path with \ to \\? - javascript

I use jquery to get the path of out an html img element like this:
path = $("#img_elemnt_id).attr('src')
It gives me a string
path = "C:\User\pic.jpg"
I need to use that string in a function but it only works if the path is like this
path ="C:\\User\\pic.jpg"
Any idea how to do this?
UPDATE: YOUR ANSWERS DO NOT WORK.
path = "C:\\User\\pic.jpg"
works in the function but your answers do not work.
path = "C:\User\pic.jpg"
path = path.replace('\\,'\\\\')
console.log(path)
outputs
C:Userpic.jpg

var path = 'C:\\User\\pic.jpg';
console.log(path);
path = path.replace(/\\/g,'\\\\');
console.log(path);
If path is having single backslash characters, those will be considered as an escape sequence along with the character(s) following them.

The flaw here is that you're declaring your string wrong in the first place:
path = "C:\User\pic.jpg"
console.log(path)
// => C:Userpic.jpg
It's already broken by this point. You must express it correctly in the first
place or the backslash will break things:
path = "C:\\User\\pic.jpg"
console.log(path)
// => C:\User\pic.jpg
This is because \U and \p get interpreted as literal u and p. Beyond that point there is no recovering the "missing" characters because this is how JavaScript's string syntax works. The second version uses \\ which is literal backslash and that avoids the issue.
If you're pulling this from an HTML element it's a different story. The backslashes should be properly encoded if and only if you properly supplied the src attribute in the first place.
If you use file:// path specifiers you can use regular slash instead of backslash and avoid all of this mess which I strongly encourage you to do.
Edit:
Now if you have no control over the src attribute, which is where this should be set properly in the first place, you could try and fix it like:
path = 'path:///' + $('id').attr('src').replace(/\\/, '/');

Use replace
path = path.replace(/\\/g, "\\\\");
I edited to include the global 'g' flag, to make it a correct solution.

Related

Why isn't .replace() working on a large generated string from escodege.generate()?

I am attempting to generate some code using escodegen's .generate() function which gives me a string.
Unfortunately it does not remove completely the semi-colons (only on blocks of code), which is what I need it to do get rid of them myself. So I am using the the .replace() function , however the semi-colons are not removed for some reason.
Here is what I currently have:
generatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions)
const cleanGeneratedCode = generatedFile.replace(';', '')
console.log('cleanGeneratedCode ', cleanGeneratedCode) // string stays the exact same.
Am I doing something wrong or missing something perhaps?
As per MDN, if you provide a substring instead of a regex
It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
So, the output probably isn't exactly the same as the code generated, but rather the first semicolon has been removed. To remedy this, simply use a regex with the "global" flag (g). An example:
const cleanGenereatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions).replace(/;/g, '');
console.log('Clean generated code: ', cleanGeneratedCode);

Regex or standard substring solution to remove Wordpress image sizing from filename

I need to remove the Wordpress width and height details from an image path using Javascript, rather than pulling it from the full image. E.g:
imagePath = "http://localhost:8888/test/wp-content/uploads/2016/12/P1010050-700x525.jpg"
I need to convert imagePath into imagePath = "http://localhost:8888/test/wp-content/uploads/2016/12/P1010050.jpg"
It is not always the same path, and not always a jpg, but it will always be -123x123 that needs to be removed.
Am I better off doing a regex expression for this (and if so, what pattern do I need?) or should I take the end after the last - off, and then take the file extension off, and then reconstruct the string with concatenation?
The solution using String.prototype.replace() function with specific regex pattern:
var imagePath = "http://localhost:8888/test/wp-content/uploads/2016/12/P1010050-700x525.jpg",
replaced = imagePath.replace(/\-[^-]+(\.\w+)$/, '$1');
console.log(replaced);

Get the full path of all files of some types from a html file and put them into an array using js/jQuery

I need to get the paths from something like this:
<object>
<p>https://bla-bla-bla/thing.flv</p>
</object>
<p>level/thing.mp3</p>
<ul>
<li>https://thing/otherthing/thing.srt<li></ul>
On the other hand, the files can be anywhere inside the html file.
I tried some possibilities, but without success.
Any clue?
Thanks a lot!
I need to get some file names with the proper address and put them into an array:
myArray[0]='https://bla-bla-bla/othername.flv'
myArray[1]='/level/name.mp3'
myArray[2]='https://text/othertext/name.srt'
..and so on
I'm very close to solve it using regexp, I did:
var str = document.getElementById("content").innerHTML;
var res = str.match(/=http.*?.flv/gi);
In this case, I get the excerpt, but I get the whole thing around it.
eg.
I need this:
'https://this/otherthing/thing.srt'
But I getting this
'more https stuff from other url ...https://this/otherthing/thing.srt even more text...'
uniques url's, not a giant string with the first http ending with the first .srt. I need a valid path.
Since .* grabs as many matching characters as it can, you need to be more specific about what can and can't be in the middle.
Try:
var res = str.match(/https?:\/\/\S+\.flv/gi);
where \S grabs as many non-whitespace characters as it can.
To exclude certain characters, use [^...]:
var res = str.match(/https?:\/\/[^\s;]+\.flv/gi);
Alternatively, just make your .* lazy instead of greedy with a well-placed ?:
var res = str.match(/http.*?\.flv/gi);

Using Regex to match the middle of a path?

I have a var showNo that's an input for the beginning of a directory.
example: var showNo = "101B"
After showNo are characters that include spaces and other junk set up on the network set by another department.
example: /101B A Trip to the Beach/
I need to use sub directories inside of this one:
example: /101B A Trip to the Beach/assets/tools/
Is there a way to use regex and the variable to avoid scanning all of the directories and trying to match a substring of the first 4 characters?
var directory = str.match(/\/101B[^\/]+\//)[0];
Will match to the first directory name that starts with you variable.
More importantly the idea is as follows :
Match the first four character string literal that starts with a directory slash.
Then match any character that is not a directory slash. The "is not" is indicated by the ^.
Then repeat 2 an additional 0 or more times.
Finally match the directory slash.
I suspect you had trouble with the "anything that is NOT" character class. It is sometimes tricky but once you get it it is a very useful short cut.
--edit--
Actually on re reading I suspect you had trouble with using the variable inside the regex, correct?
That's easy enough, too, once you know how.
You can construct it as a string first:
var regex_string = "/" + showNo + "[^/]+/";
And then "compile" it into a regex which you can use as normally :
var regex_dir = RegExp(regex_string);
var directory = str.match(regex_dir);
Hope this helps!

Javascript string replace of dots (.) within filenames

I'm trying to parse and amend some html (as a string) using javascript and in this html, there are references (like img src or css backgrounds) to filenames which contain full stops/periods/dots/.
e.g.
<img src="../images/filename.01.png"> <img src="../images/filename.02.png">
<div style="background:url(../images/file.name.with.more.dots.gif)">
I've tried, struggled and failed to come up with a neat regex to allow me to parse this string and spit it back out without the dots in those filenames, e.g.
<img src="../images/filename01.png"/> <img src="../images/filename02.png"/>
<div style="background:url(../images/filenamewithmoredots.gif)">
I only want to affect the image filenames, and obviously I want to leave the filetype alone.
A regex like:
/(.*)(?=(.gif|.png|.jpg|.jpeg))
allows me to match the main part of the filename and the extension seperately, but it also matches across the whole of the string, not just within the one filename I want.
I have no control over the incoming html, I'm just consuming it.
Help me please overflowers, you're my only hope!
I agree that this is not a problem suitable for regular expression, much less one neat expression.
But I trust that you are not here to hear that. So, in case you want to keep the input as string...
var src, result = '<img src="../images/filename.01.png"> <img src="../images/filename.02.png"><div style="background:url(../images/file.name.with.more.dots.gif)">';
do {
src = result;
result = src.replace( /((?:url(\()|href=|src=)['"]?(?:[^'"\/]*\/)*[^'"\/]*)\.(?=[^\.'")]*\.(?:gif|png|jpe?g)['")>}\s])/g, '$1' );
} while (result != src)
Basically it keeps removing the second last dot of images url's filenames until there are none. Here is a breakdown of the expression in case you need to modify it. Tread lightly:
( start main capturing group since js regx has no lookbehind.
(?:url(\()|href=|src=)['"]? Start of an url. it would be safer to force url() to be properly quoted so that we can use back reference, but unfortunately your given example is not.
(?:[^'"\/]*\/)* Folder part of the url.
[^'"\/]* Part of the file name that comes before second last dot.
) close main group.
\. This is the second last dot we want to get rid of.
(?= Look behind.
[^\.'")]* Part of the file name that goes between second last dot and last dot.
\.(?:gif|png|jpe?g) Make sure the url ends in image extension.
['")>}\s] Closing the url, which can be a quote, ')', '>', '}', or spaces. Should user back reference here if possible. (Was ['"]?\b when first answered)
) End of look behind.
Consider using the DOM instead of regular expressions. One way is to create fake elements.
var fake = document.createElement('div');
fake.innerHTML = incomingHTML: // Not really part of JS standard but all the 'main' browsers support it
var background = fake.childNodes[0].style.background;
// Now use a regex if need be: /url\(\"?(.*)\"?\)/
// If img is at childNodes[1]
var url = fake.childNodes[1].src;
With jQuery this is far easier:
$(incomingHTML).find('img').each(function() { $(this).attr('src'); });
Your problem is the greedy match in .*. Maybe better try something like this
([^\/]*)(?=(.gif|.png|.jpg|.jpeg))
[^\/] is a character class that matches every character but slashes
another point is, you need to escape the . to match it literally
([^\/]*)(?=\.(gif|png|jpg|jpeg))
The problem is that . means "any character".
Escape it:
/(.*)(?=(\.gif|\.png|\.jpg|\.jpeg))

Categories