Want to remove various strings from filename before save - javascript

I have a JSX script I've written for Photoshop and at the end of this script, before saving, I want to check the filename for various strings and remove them if they exist. What I've written so far only removes the first element in the array it encounters - in the case below it hits the regex and then moves on to save.
An example of a filename encountered is: "PRNT-AB-Navy Blush Oil pallet painting-18x24--REV 27x21.jpg"
What I want the resulting name to be is: "AB-Navy Blush Oil pallet painting"
So I need a little help understanding how can I remove all elements of the array that exist in any given filename?
var array = ["PRNT-", "--REV ", "-REV ", ".jpg", ".tif", ".psd", new RegExp(/\d+[x]\d+/g)];
var docName = activeDoc.name
for (var i = array.length; i >= 0; i--) {
var newName = docName.replace(array[i], '');
}
Thanks!

Welcome to Stack Overflow.
I haven't worked out your file name convention but this will replace the string with what you want without having to loop over each element.
var s = "PRNT-AB-Navy Blush Oil pallet painting-18x24--REV 27x21.jpg";
alert(replace_filename(s));
function replace_filename(str)
{
var rexp = new RegExp(/PRNT-|-\d*x\d*|--REV\s+\d*x\d*|.jpg|.tif.psd/gim);
return str.replace(rexp, "");
}
// AB-Navy Blush Oil pallet painting

Related

Find the index of a string in Javascript with help of first three characters

I have numerous tsv files each with header row. Now one column name in header row is age. In few files, column name is age while in other files it has EOL charcter such as \r \n.
Now how can i use str.indexOf('age') function so that i get index of age irrespective of column name age with EOL character such as \n , \r etc..
Foe eg:
tsv file1:
Name Address Age Ph_Number
file 2:
Name Address Age/r
file 3:
Name Address Age\n
I am trying to find index of age column in each files header row.
However when i do-
header.indexOf('age')
it gives me result only in case of file1 because in other 2 files we have age as age\r and age\n..
My question is how should i find index of age irrespective of \r \n character along with age in header row.
i have following script now:
var headers = rows[0].split('\t');
if (file.name === 'subjects.tsv'){
for (var i = 0; i < rows.length; i++) {
var ageIdColumn = headers.indexOf("age");
console.log(headers)
As I stated in the comments, indexOf() returns the starting position of the string. It doesn't matter what comes after it:
var csvFile1 = 'column1,column2,column3,age,c1r1';
var csvFile2 = 'column1,column2,column3,age\r,c1r1';
var csvFile3 = 'column1,column2,column3,age\n,c1r1';
console.log(csvFile1.indexOf("age"));
console.log(csvFile2.indexOf("age"));
console.log(csvFile3.indexOf("age"));
If you specifically want to find the versions with the special characters, just look for them explicitly:
var csvFile4 = 'column1,age\r,column2,column3,age\n,c1r1';
console.log(csvFile4.indexOf("age\r"));
console.log(csvFile4.indexOf("age\n"));
Lastly, it may be that you are confused as to what, exactly indexOf() is supposed to do. It is not supposed to tell you where all occurrences of a given string are. It stops looking after the first match. To get all the locations, you'd need a loop similar to this:
var csvFile5 = 'column1,age\r,column2,age, column3,age\n,c1r1';
var results = []; // Found indexes will be stored here.
var pos = null; // Stores the last index position where "age" was found
while (pos !== -1){
// store the index where "age" is found
// If pos is not null, then we've already found age earlier and we
// need to start looking for the next occurence 3 characters after
// where we found it last time. If pos is null, we haven't found it
// yet and need to start from the beginning.
pos = csvFile5.indexOf("age", pos != null ? pos + 3 : pos );
pos !== -1 ? results.push(pos) : "";
}
// All the positions where "age" was in the string (irrespective of what follows it)
// are recorded in the array:
console.log(results);

How to extract a specific text from a string. The hard part is the desired text changes periodically

I have an HTML document which contains this text somewhere in it
function deleteFolder() {
var mailbox = "CN=John Urban,OU=Sect-1,DC=TestServer ,DC=acme,DC=com";
var path = "/Inbox/";
//string of interest: "CN=John Urban,OU=Sect-1,DC=TestServer ,DC=acme,DC=com"
I just want to extract this text and store it in a variable in C#. My problem is that string of interest will slightly change each time the page is loaded, something like this:
"CN=John Urban,OU=Sect-1,DC=TestServer ,DC=acme,DC=com"
"CN=Jane Doe,OU=Sect-1,DC=TestServer ,DC=acme,DC=com"
etc....
How do I extract that ever changing string, without regular expression?
Is it always a function deleteFolder() which has its first line as var mailbox = "somestring"? And you are interested in somestring?
Based on the requirements you told us, could just search your string containing the HTML for var mailbox =" and then the next " and take all text between these two occurrences.
var htmlstring= "..."; //
var i1 = htmlstring.IndexOf("var mailbox = \"");
var i2 = i1 >= 0 ? htmlstring.IndexOf("\"", i1+15) : -1;
var result = i2 >= 0 ? htmlstring.Substring(i1+15, i2-(i1+15)): "not found";
VERY, VERY ugly, not maintainable, but without more information, I can't do any better. However Regex would be much nicer!

javascript removing characters from multiple strings using a for loop

I'm reading a log file using file reader and then want to do some text manipulation using javascript, to use the read data further in my program. So far I managed to split my input by lines, but now that I want to format the specific strings in the array nothing happens. Is this due to not declaring the array globally? Basically I wanted to do a for loop that checks all the strings inside my array and remove " " (four blank spaces) that appear at the start for some of my strings. This is my code
$("#draftlog").change(function() {
var logFile = $('#draftlog').get(0).files[0];
//gets first file from draftlog
var reader = new FileReader;
reader.readAsText(logFile);
reader.onload = function(e) {
var rawLog = reader.result;
//reads first file from draftlog as text
var re=/\r\n|\n\r|\n|\r/g;
arrayOfLines = rawLog.replace(re,"\n").split("\n");
//splits the text into an array of strings for every new line
for(x=0;x<arrayOfLines.length;x++) {
arrayOfLines[x].replace(/ /g,'');
}
console.log(arrayOfLines);
};
});
my input will typicaly look like this:
Event #: 7952945
Time: 5.2.2015 17:14:54
Players:
TheDoktorJot
Arlekin
Jokulgoblin
Felo
Petrolit
Greyjoy
--> Susti
themuse1975
n0sfea
------ FRF ------
Pack 1 pick 1:
Abzan Runemark
Rakshasa's Disdain
Reach of Shadows
Grim Contest
Aven Skirmisher
Lotus Path Djinn
Formless Nurturing
Tasigur's Cruelty
Temur Battle Rage
Return to the Earth
--> Temur Sabertooth
Fascination
Jeskai Barricade
Arcbond
Rugged Highlands
Pack 1 pick 2:
Sandblast
Sultai Runemark
Jeskai Sage
Hooded Assassin
Pressure Point
Gore Swine
Whisperer of the Wilds
Mardu Runemark
Ambush Krotiq
Write into Being
Qarsi High Priest
Hewed Stone Retainers
Wardscale Dragon
--> Mastery of the Unseen
Strings are immutable, you have to write it back
for(x=0;x<arrayOfLines.length;x++) {
arrayOfLines[x] = arrayOfLines[x].replace(/ /g,'');
}
You could also just trim it to remove leading and following whitespace
arrayOfLines[x] = arrayOfLines[x].trim();

Javascript - Removing part of string.

I've got a script which takes the filename from a file input on a form and puts it into a text field after stripping away some details which aren't required.
All files I upload will be labeled with a key word
Note that this is for a Chrome extension so X-browser support isn't necessary.
var filename = $("uploaded_data").val().toLowerCase();
filename = filename.replace(/_/g, " ").replace(/-/g, " ").replace("c:\\fakepath\\", "");
type_index[1] = filename.indexOf("red");
type_index[2] = filename.indexOf("blue");
type_index[3] = filename.indexOf("green");
type_index[4] = filename.indexOf("purple");
type_index[5] = filename.indexOf("magenta");
for (i=0 ; i > -1 ; i++ ) {
if (type_index[i] > -1)
{
filename_final = filename.substring(type_index[i]);
break;
}
}
$("#material_title").val(filename_final);
Now this code works fine, however, I don't want the colour to be part of the file name.
For example, if the input file was called 'test_red_name_low.jpg' the text field should be 'name low.jpg'. Currently, the code above outputs 'red name low.jpg'. Other times, the filename might be 'this_is_a_test-blue_happy.jpg', which should output 'happy.jpg'.
The type_index array will eventually hold a very large number of values so a replace would be a very long winded way of doing it.
Any suggestions on a way around this?
This regex will do it.
// add as many colors you like here.
var colors = ['red','green', 'blue', 'magenta', 'purple'];
filename = filename.replace(/-|_|c:\\fakepath\\/g,' ')
.replace(new RegExp("("+colors.join("|")+")", "g"), " ")
.replace(/.* /,'').trim()

Transposing music using javascript or jquery

I have a chord chart application that I wrote and I would like to allow users to transpose the key of the chart using an onClick handler.
My chart looks like this
{C}My name is Blanket, {F}And I can run fast
The chords inside the brackets appear above the letter it preceeds.
I would like to use javascript or jquery in order to do this. How would I go about creating this transpose button? Any help is appreciated. Thank you in advance.
EDIT
So here's what I came up with...
$('.transposeUp').click(function(){
$('.chord').each(function(){
var currentChord = $(this).text(); // gathers the chord being used
if(currentChord == $(this).text()){
var chord = $(this).text().replace("F#", "G")
}
//... the if statements continue though every chord
//but I didn't place them here to save space
});
});
So here is the problem...
I have a slash chord in the mix (G/B), It changes the be on transpose but because it changes the "B" the chord is now (G/C) which is not the same as the "currentChord" so it doesn't change the G when it gets to its respective if condition. Until I have transposed enough where the Chord is eventualy (G/G) then the first "G" starts transposing leaving the last "G" the same. Any ideas? Again your knowledge and help is greatly appreciated. Thanks in advance.
You need to match the chords sequentially so that you can update them one at a time. If you try to match everything at once you'll run into problems like you described, because you keep matching the same chord over and over again.
A good way to accomplish this would be with regular expressions to parse and split the chord. Once you have the matching chord values, use an array of chords to find the next/previous chord to transpose. Here is some sample code I have developed as a demo:
<p><span class="chord">{C}</span>My name is Blanket,</p>
<p><span class="chord">{G / B}</span>And I can run fast</p>
<p>
<input id="transposeDown" type="button" value="Down" /> |
<input id="transposeUp" type="button" value="Up" />
</p>
var match;
var chords =
['C','C#','D','Eb','E','F','F#','G','Ab','A','Bb','B','C',
'Db','D','D#','E','F','Gb','G','G#','A','A#','C'];
var chordRegex = /C#|D#|F#|G#|A#|Db|Eb|Gb|Ab|Bb|C|D|E|F|G|A|B/g;
$('#transposeUp').click(function() {
$('.chord').each(function() {
var currentChord = $(this).text();
var output = "";
var parts = currentChord.split(chordRegex);
var index = 0;
while (match = chordRegex.exec(currentChord))
{
var chordIndex = chords.indexOf(match[0]);
output += parts[index++] + chords[chordIndex+1];
}
output += parts[index];
$(this).text(output);
});
});
$('#transposeDown').click(function() {
$('.chord').each(function() {
var currentChord = $(this).text();
var output = "";
var parts = currentChord.split(chordRegex);
var index = 0;
while (match = chordRegex.exec(currentChord))
{
var chordIndex = chords.indexOf(match[0],1);
output += parts[index++] + chords[chordIndex-1];
}
output += parts[index];
$(this).text(output);
});
});
Sample demo: http://jsfiddle.net/4kYQZ/2/
A couple of things to notice:
I took #gregp's idea of having multiple copies of the key list so that I can handle both sharps and flats. The first scale includes the preferred #/b which will be used during transposing. The second scale includes the other formats so that if the music includes them, they will transpose correctly. For instance, since Eb is in the first scale, it will be used instead of D# as you are transposing up and down; however, if there is a D# in the music to begin with, it will correctly move to D/E (with the caveat that if you move back, it will become an Eb again). Feel free to modify the preferred scale - I used my educated judgment based on personal music experience.
The regular expression has to have the sharped/flatted keys first, otherwise a C# would be just as easily matched as a C when that's not correct.
I have C at the beginning and the end of the array so that I can start at any location and move both directions without passing the end of the array. In order for this to work, the transposeDown code has an extra parameter in the call to chords.indexOf to start at position 1 so it matches the last C in the array instead of the first C. Then when it attempts to move to the previous element, it doesn't pass the beginning of the array.
I'm splitting the chord as well using the regular expression, which is redundant, but it makes it super-easy to recompose the final string back together - by interleaving the original string parts with the updated chord keys (don't forget the last piece at the end!).
I'm using elements instead of classes for your buttons.
Hope this helps!
Update 1: Per comment by OP, the use of indexOf on arrays is not supported by pre-ie9. This can be solved by using a helper function that does the same thing:
function arrayIndexOf(arr, match)
{
for (var i = 0; i < arr.length; i++)
if (arr[i] == match)
return i;
return -1;
}
And this line
var chordIndex = chords.indexOf(match[0]);
would be replaced with:
var chordIndex = arrayIndexOf(chords, match[0]);
See updated sample demo: http://jsfiddle.net/4kYQZ/11/
Using jQuery, you're spoiled for choice for binding click handlers. There's .click(), .delegate(), .live(), and many others. It wouldn't make sense to reproduce what the APIs already tell you, but I can say this: learning how to bind the click is the smallest part of the overall problem, and even capturing the chord name with .text() is going to be trivial once you've had a look at the jQuery API.
The tricky part is going to be the logic of transposing itself. You'll need to take the knowledge you already have (for example, going from E to F is only a half-step; there's no E# or Fb) and make it work as code.
My apologies for general advice rather than code samples, but my advice is to have two arrays, one containing all the chords in terms of sharps, one with all the chords in terms of flats.
You could do a bit of cheating, too: instead of logic to wrap around to the beginning (say, C in position 0), just have your arrays duplicated:
["C","C#","D","D#","E","F","F#","G","G#","A","B","C","C#","D","D#","E","F","F#","G","G#","A","B"]
Then find the first occurence of the chord name, move ahead the desired number of stops, and you'll still have the right string.
Call function transpose for up:
text = transpose(text, 1);
Call function transpose for down:
text = transpose(text, -1);
Function:
function transpose(text, amount){
var lines = new Array();
var chord = new Array();
var scale = ["C","Cb","C#","D","Db","D#","E","Eb","E#","F","Fb","F#","G","Gb","G#",
"A","Ab","A#","B","Bb","B#"];
var transp = ["Cb","C","C#","Bb","Cb","C","C","C#","D","Db","D","D#","C","Db","D",
"D","D#","E","Eb","E","F","D","Eb","E","E","E#","F#","E","F","F#",
"Eb","Fb","F","F","F#","G","Gb","G","G#","F","Gb","G","G","G#","A",
"Ab","A","A#", "G","Ab","A","A","A#","B","Bb","B","C","A","Bb","B",
"B","B#","C#"];
var inter = '';
var mat = '';
lines = text.split("\n");
for(var i in lines){
if(i%2===0){
chord = lines[i].split(" ");
for(var x in chord){
if(chord[x]!==""){
inter = chord[x];
var subst = inter.match(/[^b#][#b]?/g);
for(var ax in subst){
if(scale.indexOf(subst[ax])!==-1){
if(amount>0){
for(ix=0;ix<amount;ix++){
var pos = scale.indexOf(subst[ax]);
var transpos = 3*pos-2+3;
subst[ax] = transp[transpos+1];
}
}
if(amount<0){
for(ix=0;ix>amount;ix--){
var pos = scale.indexOf(subst[ax]);
var transpos = 3*pos-2+3;
subst[ax] = transp[transpos-1];
}
}
}
}
chord[x]=subst.join("");
}
}
lines[i] = chord.join(" ");
}
}
return lines.join("\n");
}
The first line is transpose and the second does not, and sequentially.

Categories