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()
Related
I have a sentence stored in a variable.That sentence I need to extract into 4 parts depends on sentence which I have put into variables in my code,I can able to extract here and get into console but I am not getting the whole text of inside the bracket,only I am getting first words.Here is the code below.Can anyone please help me.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages">
SCRIPT
$(document).ready(function() {
regex = /.+\(|\d. \w+/g;
maintext = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
matches = maintext.match(regex);
text_split0 = matches[0].slice(0, -1);
text_split1 = matches[1];
text_split2 = matches[2];
text_split3 = matches[3];
text_split4 = matches[4];
console.log(text_split0);
console.log(text_split1);
console.log(text_split2);
console.log(text_split3);
console.log(text_split4);
$(".messages").append('<li>'+text_split0+'</li><li>'+text_split1+'</li><li>'+text_split2+'</li><li>'+text_split3+'</li><li>'+text_split4+'</li>');
// $("li:contains('undefined')").remove()
});
function buildMessages(text) {
let messages = text.split(/\d\.\s/);
messages.shift();
messages.forEach((v)=>{
let msg = v.replace(/\,/,'').replace(/\sor\s/,'').trim();
$('.messages').append(`<li>${msg}</li>`);
// console.log(`<li>${msg}</li>`);
});
}
let sentenceToParse = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
buildMessages(sentenceToParse);
Use the split function on the String, keying on the digits (e.g. 1.), you will get the preface and each of the steps into an array.
Use the shift function on the Array removes the unneeded preface.
Use forEach to iterate over the values in the array, clean up the text.
Using replace to first remove commas, then remove or with spaces on either side.
Use trim to remove leading and training whitespace.
At this point, your array will have sanitized copy for use in your <li> elements.
If you're only concerned with working through a regex and not re-factoring, the easiest way may be to use an online regex tool where you provide a few different string samples. Look at https://www.regextester.com/
Ok, Try another approach, cause regex for this isn't the best way. Try this:
$(document).ready(function() {
// First part of sentence.
var mainText = "Welcome to project, are you a here(";
// Users array.
var USERS = ['new user', 'test user', 'minor Accident', 'Major Accident'];
var uSize = USERS.length;
// Construct string & user list dynamically.
for(var i = 0; i < uSize; i++) {
var li = $('<li/>').text(USERS[i]);
if(i === uSize - 1)
mainText += (i+1) + ". " + USERS[i] + ")";
else if(i === uSize - 2)
mainText += (i+1) + ". " + USERS[i] + " or ";
else
mainText += (i+1) + ". " + USERS[i] + " , ";
$(".messages").append(li);
}
console.log(mainText); // You will have you complete sentence.
}
Why that way is better? Simple, you can add or remove users inside the user array. String together with your user list will be updated automatically. I hope that help you.
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
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!
I am trying to write a script to edit the content of a Text Layer in Photoshop CS6. Is that possible?
I have about 2000 images that I need to process for a work project. First I am adding the filename of each image as a text layer in Photoshop using a javascript I already have (see below). A sample filename is "UCMC_0018015 D FSH E." My script successfully adds this filename to the image as a text layer in Photoshop.
However, I would then like to edit the text layer in order to replace the underscore with a space, and removing " FSH E" from the end of the text string (all file names have these elements, but the numbers in the file name varies from file to file). Can anyone help me with the script I need to do this? I am new to writing and running scripts, but I am doing my best to learn on the job. Any advice you can give me would be appreciated.
Here is my current script for adding the filename to the image. I am not sure if I can edit it or if I will need to write a new script to edit the text layer. Thank you for your help!
//Check if a document is open
if ( documents.length > 0 )
{
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PERCENT;
try
{
var docRef = activeDocument;
// Create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
//Set your parameters below this line
//If you wish to show the file extension, change the n to y in the line below, if not use n.
var ShowExtension = "n";
// Insert any text to appear before the filename, such as your name and copyright info between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextBefore = "";
// Insert any text to appear after the filename between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextAfter = "";
// Set font size in Points
myTextRef.size = 30;
//Set font - use GetFontName.js to get exact name
myTextRef.font = "Times New Roman";
//Set text colour in RGB values
var newColor = new SolidColor();
newColor.rgb.red = 0;
newColor.rgb.green = 0;
newColor.rgb.blue = 0;
myTextRef.color = newColor;
// Set the position of the text - percentages from left first, then from top.
myTextRef.position = new Array( 75, 98);
// Set the Blend Mode of the Text Layer. The name must be in CAPITALS - ie change NORMAL to DIFFERENCE.
myLayerRef.blendMode = BlendMode.NORMAL;
// select opacity in percentage
myLayerRef.opacity = 100;
// The following code strips the extension and writes tha text layer. fname = file name only
di=(docRef.name).indexOf(".");
fname = (docRef.name).substr(0, di);
//use extension if set
if ( ShowExtension == "y" )
{
fname = docRef.name
}
myTextRef.contents = TextBefore + " " + fname + " " + TextAfter;
}
catch( e )
{
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
throw e;
}
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
}
else
{
alert( "You must have a document open to add the filename!" );
}
You can use a regular expression to remove all the whitespace and replace them with underscores. As far as I understand you can do a literal replace for " FSH E" to an empty string first. If those letters are different then you'll have to use a different tactic. But this will work for now. This is the basic part of the code that you need.
var myFileName = "UCMC_0018015 D FSH E";
// remove " FSH E"
myFileName = myFileName.replace(" FSH E", "");
// replace whitespce with underscores
myFileName = myFileName.replace(/\s/gi, "_");
alert(myFileName);
Your final code should look like this
//Check if a document is open
if ( documents.length > 0 )
{
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PERCENT;
try
{
var docRef = activeDocument;
// Create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
//Set your parameters below this line
//If you wish to show the file extension, change the n to y in the line below, if not use n.
var ShowExtension = false;
// Insert any text to appear before the filename, such as your name and copyright info between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextBefore = "";
// Insert any text to appear after the filename between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextAfter = "";
// Set font size in Points
myTextRef.size = 30;
//Set font - use GetFontName.js to get exact name
myTextRef.font = "Times New Roman";
//Set text colour in RGB values
var newColor = new SolidColor();
newColor.rgb.red = 0;
newColor.rgb.green = 0;
newColor.rgb.blue = 0;
myTextRef.color = newColor;
// Set the position of the text - percentages from left first, then from top.
myTextRef.position = new Array( 75, 98);
// Set the Blend Mode of the Text Layer. The name must be in CAPITALS - ie change NORMAL to DIFFERENCE.
myLayerRef.blendMode = BlendMode.NORMAL;
// select opacity in percentage
myLayerRef.opacity = 100;
// The following code strips the extension and writes tha text layer. fname = file name only
var fname = docRef.name;
// code changes here.
// remove " FSH E"
fname = fname.replace(" FSH E", "");
// replace whitespaces with underscores
fname = fname.replace(/\s/gi, "_");
//use extension if set
if ( ShowExtension == true )
{
di =(fname).lastIndexOf(".");
fname = (fname).substr(0, di);
}
myTextRef.contents = TextBefore + " " + fname + " " + TextAfter;
}
catch( e )
{
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
throw e;
}
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
}
else
{
alert( "You must have a document open to add the filename!" );
}
As your new to JavasScript, I'd like to point out that you have the showextension variable as a string. It's probably easier for it to be a Boolean. So it can only ever be TRUE or FALSE. A string could be, well... anything.
Another point is you had indexOf to find the extension. which will work fine. Unless you have a filename such as "my.lovely.photo.jpg"; whereas your extension would be "lovely.photo.jpg" Using lastIndexOf, as you might guess, finds the index of the item near the end of the string.
Struggling with the below script. I modified a script found so that it extracts all stories as txt files and saves the txt file with the filename of the the text in the paragraph.
It turned out we didn't want all stories extracted however the ones we did want had a set paragraph style for the first paragraph of story.
The part im struggling with is the syntax of the if statement that checks what the currently applied paragraph style is.
any help appreciated, sorry if my problem is unclear
main();
function main(){
//Make certain that user interaction (display of dialogs, etc.) is turned on.
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
if(app.documents.length != 0){
if (app.activeDocument.stories.length != 0){
myDisplayDialog();
}
else{
alert("The document does not contain any text. Please open a document containing text and try again.");
}
}
else{
alert("No documents are open. Please open a document and try again.");
}
}
function myDisplayDialog(){
with(myDialog = app.dialogs.add({name:"ExportAllStories"})){
//Add a dialog column.
myDialogColumn = dialogColumns.add()
with(myDialogColumn){
with(borderPanels.add()){
staticTexts.add({staticLabel:"Export as:"});
with(myExportFormatButtons = radiobuttonGroups.add()){
radiobuttonControls.add({staticLabel:"Text Only", checkedState:true});
radiobuttonControls.add({staticLabel:"RTF"});
radiobuttonControls.add({staticLabel:"InDesign Tagged Text"});
}
}
}
myReturn = myDialog.show();
if (myReturn == true){
//Get the values from the dialog box.
myExportFormat = myExportFormatButtons.selectedButton;
myDialog.destroy;
myFolder= Folder.selectDialog ("Choose a Folder");
if((myFolder != null)&&(app.activeDocument.stories.length !=0)){
myExportAllStories(myExportFormat, myFolder);
}
}
else{
myDialog.destroy();
}
}
}
//myExportStories function takes care of exporting the stories.
//myExportFormat is a number from 0-2, where 0 = text only, 1 = rtf, and 3 = tagged text.
//myFolder is a reference to the folder in which you want to save your files.
function myExportAllStories(myExportFormat, myFolder){
for(myCounter = 0; myCounter < app.activeDocument.stories.length; myCounter++){
myStory = app.activeDocument.stories.item(myCounter);
myID = myStory.id;
switch(myExportFormat){
case 0:
myFormat = ExportFormat.textType;
myExtension = ".txt"
break;
case 1:
myFormat = ExportFormat.RTF;
myExtension = ".rtf"
break;
case 2:
myFormat = ExportFormat.taggedText;
myExtension = ".txt"
break;
}
if(myStory.paragraphs[0].appliedParagraphStyle = "PRODUCT HEADING"){
myFileName = myStory.paragraphs[0].contents;
myFilePath = myFolder + "/" + myFileName;
myFile = new File(myFilePath);
myStory.exportFile(myFormat, myFile);
}
}
}
The type of appliedParagraphStyle is [Object ParagraphStyle], so you need to compare it against either another paragraph style (i.e., app.activeDocument.paragraphStyles.item("PRODUCT HEADING") which does return a paragraph style), or compare the names of the styles.
Also, do not use = to test. A single = is 'apply'; to test for (in)equality, use a double ==. (Javascript also has a 'strictly equals' comparison: ===, but in this case it should not be used.)
Your script will work if you change the comparison line to
if (myStory.paragraphs[0].appliedParagraphStyle.name == "PRODUCT HEADING")
Additionally, the line
myFileName = myStory.paragraphs[0].contents;
grabs the entire paragraph to use for a file name, and usually this will include the paragraph return at the end. (The exception is when this paragraph is the last one in a story.) Since you use this string as a new file name, you must remove the paragraph return if it's there. That can be done in several ways, but the easiest is to use a RegEx replace:
myFileName = myStory.paragraphs[0].contents.replace(/\s*$/,'');
because that will also remove all stray spaces and tabs at the end for free.