I got a few names of automatically generated folders on a site.
They are named like this:
"folder_photos_today_1"
"folder_photos_yesterday_2"
"folder_photos_future_3"
...
"folder_potos_more_11"
The number at the end of each name is an ID for the folder, thats generated by a Plugin.
Now I'd like to display these folder-names like:
"folder photos today"
"folder photos yesterday"
Converting the names with javascript (pureJS or jQuery, doesn't matter) I thought about finding the last _
in the name and deleting it and everything after it. Then search for other _
and replace them with whitespaces.
The problem I have:
How do I find the last character of one type (the last _
) with JS?
I got a few names of automatically generated folders on a site.
They are named like this:
"folder_photos_today_1"
"folder_photos_yesterday_2"
"folder_photos_future_3"
...
"folder_potos_more_11"
The number at the end of each name is an ID for the folder, thats generated by a Plugin.
Now I'd like to display these folder-names like:
"folder photos today"
"folder photos yesterday"
Converting the names with javascript (pureJS or jQuery, doesn't matter) I thought about finding the last _
in the name and deleting it and everything after it. Then search for other _
and replace them with whitespaces.
The problem I have:
How do I find the last character of one type (the last _
) with JS?
3 Answers
Reset to default 9lastIndexOf()
is what you want:
var index = "folder_photos_future_3".lastIndexOf('_'); // returns 20
You can then substring and replace your _
with spaces.
You could also split()
your string and discard the last value:
var words = "folder_photos_future_3".split('_');
words.pop();
words.join(' '); // "folder photos future"
Wouldn't be this oneliner simpler?
"folder_photos_today_12".replace(/_[0-9]+/g,"").replace(/_/g," ");
http://jsfiddle/sf2p4yua/
Here are some explanations:
.replace(/_[0-9]+/g,"")
replaces the bination of underscore and more that one digit after, so you'll have this string folder_photos_today
.
.replace(/_/g," ")
replaces all underscores inside the string: folder photos today
.
Hope this plunker link will help you.
http://plnkr.co/edit/V1hFEt37GzVq7AYUVUMa?p=preview
var splitFunction = function(){
var arr = ["folder_photos_today_1",
"folder_photos_yesterday_2",
"folder_photos_future_3",
"folder_photos_four_4",
"folder_photos_five_5",
"folder_photos_six_6",
"folder_photos_seven_7",
"folder_photos_eight_8",
"folder_photos_nine_9",
"folder_photos_ten_10",
"folder_potos_more_11"];
var res = [];
document.getElementById('result').innerHTML = "<b>RESULT : </b><br/>"
for (var i =0; i<arr.length; i++){
res[i] = arr[i].substr(0,arr[i].lastIndexOf('_'));
res[i] = res[i].replace(/_/g, ' ');
document.getElementById('result').innerHTML += res[i] + '<br/>';
}
}