I have tried to load an image by path that contains special characters like &#^.
When I loaded the image as below, it didn't work.
<img src="file:///test/##$%/0.png"/>
So, I've tried to use encodeURI(path), encodeURIComponent(path), but it didn't work too.
How can I do this?
You have to encode each level in your path (skip the / characters):
const path = 'file:///test/##$%/0.png'
const encodedPath = 'file://' + path.replace('file://', '').split('/').map((p) => encodeURIComponent(p)).join('/')
console.log(encodedPath)
// Output: file:///test/%40%23%24%25/0.png
Use the above output for your img tag, it will be loaded.
You cannot render them as string. If you want to use them, you must write on Numeric code or JS escape.
You can find their codes from here
As your wanted,
# : #
# : #
$ : $
Related
While I am making a URL, where it took the filename and create a folder with those names. But if the name contains "/", the URL is breaking and the undesired location is created.
Ex:
var fileDirectory = $(".username").text()+"/"+$('#class').val()+"/"+$('#projectCode').val();
when projectCode return a name with "/" , for example : magc/90 ; It create "magc" and "90" two different folder while i want it to be "magc/90" folder.
I used Replace function that works, But I want to store the Original project code here.
Anyway to do this . Thanks in advance .
Don't use / in your filenames. Most OS either use / or \ as delimiter. Some might also use ., : or >.
If you want to do something like this mgic/90 use - or _ as delimiter.
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.
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);
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);
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))