0

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?

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

This works great. My only reservation would be that I may have hundreds of colours and having to type them all would make the script very difficult to manage. Is there a way that the type_index array could be used to select a point to trim the filename?
Yes. Find the highest value from type_index. Then find first space after that index. Store it as new index. take a sub-string after this new index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.