string replace with jquery assitance - javascript

I have a string like this
"/folder1/folder2/folder3/IMG_123456_PP.jpg"
I want to use JavaScript / jQuery to replace the 123456 in the above string with 987654. The entire string is dynamic so cant do a simple string replace. For example, the string could also be
"/folder1/folder2/folder3/IMG_143556_TT.jpg"
"/folder1/folder2/folder3/IMG_1232346_RR.jpg"
Any tips on this?

"/folder1/folder2/folder3/IMG_123456_PP.jpg".replace(/\_\d{2,}/,'_987654');
Edit :
"/fo1/fo2/fol3/IMG_123456fgf_PP.jpg".replace(/\_\d{2,}[A-Za-z]*/,'_987654');

I am sure there is a better way to do this, but if you are trying to always replace the numbers of that file regardless of what they may be you could use a combination of splits/joins like this:
str = "/folder1/folder2/folder3/IMG_143556_TT.jpg" //store image src in string
strAry = str.split('/') //split up the string by folders and file (as last array position) into array.
lastPos = strAry.length-1; //find the index of the last array position (the file name)
fileNameAry = strAry[lastPos].split('_'); //take the file name and split it into an array based on the underscores.
fileNameAry[1] = '987654'; //rename the part of the file name you want to rename.
strAry[lastPos] = fileNameAry.join('_'); //rejoin the file name array back into a string and over write the old file name in the original string array.
newStr = strAry.join('/'); //rejoin the original string array back into a string.
What this will do is make it so that regardless of what directory or original name of the file name is, you can change it based on the string's structure. so as long as the file naming convention stays the same (with underscores) this script will work.
please excuse my vocab, I know it's not very good heh.

Use a regular expression
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,function($0, $1){
return $1 ? $1 + '987654' : $0;
});
example at http://www.jsfiddle.net/MZXhd/
Perhaps more comprehensible is
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var replacewith = '987654';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,'$1'+replacewith);
example at http://www.jsfiddle.net/CXAq6/

Related

Parsing file names with javascript

I have file names like the following:
SEM_VSE_SKINSHARPS_555001881_181002_1559_37072093.DAT
SEM_VSE_SECURITY_555001881_181002_1559_37072093.DAT
SEM_VSE_MEDICALCONDEMERGENCIES_555001881_181002_1559_37072093.DAT
SEM_REASONS_555001881_181002_1414_37072093.DAT
SEM_PSE_NPI_SECURITY_555001881_181002_1412_37072093.DAT
and I need to strip the numbers from the end. This will happen daily and and the numbers will change. I HAVE to do it in javascript. The problem is, I know really nothing about javascript. I've looked at both split and slice and I'm not sure either will work. These files come from a government entity which means the file name will probably not be consistent.
expected output:
SEM_VSE_SKINSHARPS
SEM_VSE_SECURITY
SEM_VSE_MEDICALCONDEMERGENCIES
SEM_REASONS
SEM_PSE_NPI_SECURITY
Any help is greatly appreciated.
This is a good use case for regular expressions. For example,
var oldFileName = 'SEM_VSE_SKINSHARPS_555001881_181002_1559_37072093.DAT',
newFileName;
newFileName = oldFileName.replace(/[_0-9]+(?=.DAT$)/, ''); // SEM_VSE_SKINSHARPS.DAT
This says to replace as many characters as it can in the set - and 0-9, with the requirement that the replaced portion must be followed by .DAT and the end of the string.
If you want to strip the .DAT, as well, use /[_0-9]+.DAT$/ as the regular expression instead of the one above.
If all the files end in .XYZ and follow the given pattern, this might also work:
var filename = "SEM_VSE_SKINSHARPS_555001881_181002_1559_37072093.DAT"
filename.slice(0,-4).split("_").filter(x => !+x).join("_")
results in:
"SEM_VSE_SKINSHARPS"
This is how it works:
drop the last 4 chars (.DAT)
split by _
filter out the numbers
join what is remaining with another _
You can also create a function out of this solution (or the other ones) and use it to process all the files provided they are in an array:
var fileTrimmer = filename => filename.slice(0,-4).split("_").filter(x => !+x).join("_")
var result = array_of_filenames.map(fileTrimmer)
Below is a solution that assumes you have your file name strings stored in an array. The code below simply creates a new array of properly formatted file names by utilizing Array.prototype.map on the original array - the map callback function first grabs the extension part of the string to tack on the file name later. Next, the function breaks the fileName string into an array delimited on the _ character. Finally, the filter function returns true if it does not find a number within the fileName string - returning true means that the element will be part of the new array. Otherwise, filter will return false and will not include the portion of the string that contains a number.
var fileNames = ['SEM_VSE_SKINSHARPS_555001881_181002_1559_37072093.DAT', 'SEM_VSE_SECURITY_555001881_181002_1559_37072093.DAT', 'SEM_VSE_MEDICALCONDEMERGENCIES_555001881_181002_1559_37072093.DAT', 'SEM_REASONS_555001881_181002_1414_37072093.DAT', 'SEM_PSE_NPI_SECURITY_555001881_181002_1412_37072093.DAT'];
var formattedFileNames = fileNames.map(fileName => {
var ext = fileName.substring(fileName.indexOf('.'), fileName.length);
var parts = fileName.split('_');
return parts.filter(part => !part.match(/[0-9]/g)).join('_') + ext;
});
console.log(formattedFileNames);

Why is JavaScript's split() method not splitting on ":"?

So to start off, a bit of context. I am pulling data from the following url: "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all" using a GET method. The data returned is a series of Pokemon names and image names in the following format.
Name1:name1.png
Name2:name2.png
...
The list is 151 items long. When I call the typeOf() method "String" is returned, so I am fairly certain it is a String I am dealing with here. What I would like to do is split the String on the delimiters of "\n" and ":".
What I would like:
Name1,name1.png,Name2,name2.png...
After some experimentation with Regex, I found that the Regex to do this was "\n|:". Using this I wrote the following line to split the String apart. I tested this Regex on https://regex101.com and it seems to work properly there.
var splitData = data.split("\n|:");
("data" is the String I receive from the url.)
But instead of splitting the String and placing the substrings into an array it doesn't do anything. (At least as far as I can see.) As such my next idea was to try replacing the characters that were giving me trouble with another character and then splitting on that new character.
data = data.replace("\n", " ");
data = data.replace("/:/g", " ");
var splitData = data.split(" ");
The first line that replaces new line characters does work, but the second line to replace the ":" does not seem to do anything. So I end up with an array that is filled with Strings that look like this.
Name1:name1.png
I can split these strings by calling their index and then splitting the substring stored within, which only confuses me more.
data = data.replace("\n", " ");
var splitData = data.split(" ");
alert(splitData[0].split(":")[1]);
The above code returns "name1.png".
Am I missing something regarding the split() method? Is my Regex wrong? Is there a better way to achieve what I am attempting to do?
Right now you are splitting on the string literal "\n|:" but to do a regex you want data.split(/[:\n]/)
The MDN page shows two ways to build a Regex:
var regex1 = /\w+/;
var regex2 = new RegExp('\\w+');
The following test script was able to work for me. I decided to use the regex in the split instead of trying to replace tokens in the string. It seemed to do the trick for me.
let testResponse = `Abra:abra.png
Aerodactyl:aerodactyl.png`;
let dataArray = testResponse.split(/\n|:/g);
let commaSeperated = dataArray.join(',');
console.log(commaSeperated);
So you can simply use regex by excluding the quotes all together.
You can look at the documentation here for regular expressions. They give the following examples:
var re = /ab+c/;
var re = new RegExp('ab+c');
See below for your expected output:
var data = `Name1:name1.png
Name2:name2.png`;
var splitData = data.split(/[\n:]/);
console.log(splitData);
//Join them by a comma to get all results
console.log(splitData.join(','));
//For some nice key value pairs, you can reduce the array into an object:
var kvps = data.split("\n").reduce((res, line) => {
var split = line.split(':');
return {
...res,
[split[0]]: split[1]
};
}, {});
console.log(kvps);
I tried and this works good.
str.split(/[:\n]/)
Here is a plunker.
plunker

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

Is it possible to get this part of a string

I wonder if it's possible to get this part of a string.
Here is my string:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
Now I want to be able to grab just this part of the string, the file name:
12391381_10205760647243398_2385261683139818614_n.jpg
I tried:
var result = /[^/]*$/.exec(""+url+"")[0];
, but it will return
user%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=4c92c4d7-8979-4478-a63d-ea190bec87cf
My Regex is wrong.
Another this is, the file extension can be .png or jpg so it's not fixed to jpg.
You could use a regex to isolate the part you want :
This works :
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
console.log((string.match(/[A-Za-z0-9_]+.(jpg|png|bmp)/))[0].substring(2));
Note that may have to be adapted depending on how much the URL string changes:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var out = string.split('?')[0].split('%2F')[2];
console.log(out); // "12391381_10205760647243398_2385261683139818614_n.jpg"
Assuming, you always have an url, first I would decode the encoded / (%2F) characters via:
var string = "www.somesite.com/o/images%2Fc834vePyJ3SFVk2iO4rU0ke1cSa2%2F12391381_10205760647243398_2385261683139818614_n.jpg?alt=media&token=7a692a38-6982-474f-bea5-459c987ae575";
var decodedUrl = decodeURIComponent(string);
and then use a regex:
decodedUrl.match(/[^/]*(?=[?])/)
Mind, that this regex assumes parameters (the part starting with ?...) are present, so if that's not the case, you might have to alter it to your needs.
If the filename always has a .jpg extension:
var url = decodeURIComponent(string);
var filename = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf(".jpg"))
If not:
url = url.substring(url.lastIndexOf("/")+1)
filename = url.substring(0,url.indexOf("?"))
Looking at the string, it appears that the file name is between the second occurrence of "%2F" and the first occurrence of "?" in the string.
The first step is to get rid of the part of the string before the second "%2F". This can be done by splitting the string at every "%2F" and taking the third element in the resulting array.
var intermediate = string.split("%2F")[2]
Then, we need to get rid of everything after the "?":
var file_name = intermediate.split("?")[0]
This should give you the file name from the URL

Regex one-liner for splitting string at nth character where n is a variable length

I've found a few similar questions, but none of them are clean one-liners, which I feel should be possible. I want to split a string at the last instance of specific character (in my case .).
var img = $('body').attr('data-bg-img-url'); // the string http://sub.foo.com/img/my-img.jpg
var finalChar = img.split( img.split(/[.]+/).length-1 ); // returns int 3 in above string example
var dynamicRegex = '/[.$`finalChar`]/';
I know I'm breaking some rules here, wondering if someone smarter than me knows the correct way to put that together and compress it?
EDIT - The end goal here is to split and store http://sub.foo.com/img/my-img and .jpg as separate strings.
In regex, .* is greedy, meaning it will match as much as possible. Therefore, if you want to match up to the last ., you could do:
/^.*\./
And from the looks, you are trying to get the file extension, so you would want to add capture:
var result = /^.*\.(.*)$/.exec( str );
var extension = result[1];
And for both parts:
var result = /^(.*)\.(.*)$/.exec( str );
var path = result[1];
var extension = result[2];
You can use the lastIndexOf() method on the period and then use the substring method to obtain the first and second string. The split() method is better used in a foreach scenario where you want to split at all instances. Substring is preferable for these types of cases where you are breaking at a single instance of the string.

Categories

Resources