AntonCooper
AntonCooper

Reputation: 73

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?

Upvotes: 0

Views: 163

Answers (1)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57640

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()

Upvotes: 1

Related Questions