Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming a string from the end in Javascript

In Javascript, how can I trim a string by a number of characters from the end, append another string, and re-append the initially cut-off string again?

In particular, I have filename.png and want to turn it into filename-thumbnail.png.

I am looking for something along the lines of:

var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);
like image 773
Ben Avatar asked Jun 04 '26 20:06

Ben


2 Answers

You can use .slice, which accepts negative indexes:

function insert(str, sub, pos) {
    return str.slice(0, pos) + sub          + str.slice(pos);
    //     "filename"        + "-thumbnail" + ".png"
}

Usage:

insert("filename.png", "-thumbnail", -4); // insert at 4th from end
like image 73
pimvdb Avatar answered Jun 06 '26 09:06

pimvdb


Try using a regular expression (Good documentation can be found at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)

I haven't tested but try something like:

var re = /(.*)\.png$/;  
var str = "filename.png";  
var newstr = str.replace(re, "$1-thumbnail.png");  
console.log(newstr);
like image 42
jcuenod Avatar answered Jun 06 '26 09:06

jcuenod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!