oneday
oneday

Reputation: 1629

Javascript - how to remove all characters after a certain set of characters?

I have a filename stored in a cookie, ex. filename.jpg but in IE for some reason it adds some characters after ".jpg"

How can I remove all the characters after ".jpg"?

I only find solutions for removing n number of characters, but the problem is that I'm not sure if the number of characters will remain constant, so I would like to treat it as undefined.

Upvotes: 1

Views: 2123

Answers (2)

neelsg
neelsg

Reputation: 4842

A very simple solution could be, for a variable named filename, use:

filename.substring(0, filename.indexOf('.jpg') + 4);

See substring and indexOf

Upvotes: 2

test30
test30

Reputation: 3654

Just use

var string="your string here";
string.replace(/(.+?\.jpg).*/, "$1");

example:

"filename.jpgSS348*%&%&$8239SomeMagicHappeningSheat.jpg".replace(/(.+?\.jpg).*/, "$1")

returns

"filename.jpg"

Note: greediness oprator .+?.

Upvotes: 1

Related Questions