Sarath Rachuri
Sarath Rachuri

Reputation: 2116

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.

Upvotes: 6

Views: 18390

Answers (4)

surajck
surajck

Reputation: 1175

str = 'image.test.jpg'

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

This accounts for having . within the name of the image

Upvotes: 11

Shouvik
Shouvik

Reputation: 11720

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.

Upvotes: 1

vaspant
vaspant

Reputation: 65

You can use javascript:

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

Upvotes: 0

Rhumborl
Rhumborl

Reputation: 16609

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>

Upvotes: 6

Related Questions