简体   繁体   中英

How to trim a string after a specific character in javascript

I'm having a string like "image.jpg". I want to save the image with its name, so i need to trim the image extension. Any methods in javascript to achieve that.

str = 'image.test.jpg'

str.slice(0,str.lastIndexOf('.'))

This accounts for having . within the name of the image

You need to take . in the base name into account. This remove the last .ext value

 var fileName = "some.image.jpg"; var baseName = fileName.replace(/\\.[^.]+$/, ''); $('div').text(baseName); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div></div> 

There is a split function offered by javascript. Essentially what you are trying to do is split the string into array of strings based on the character you need.

var str = "image.jpg";
var array = str.split(".");
array.pop();
var imageName = array.join("");

PS: This is pure javascript so you don't really need any other library.

You can use javascript:

yourString = "image.jpg";    
yourString=yourString.replace('.jpg','');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM