user951042
user951042

Reputation:

Javascript splitting

lets say i have this variable

var image = "image.jpg";

I'm trying to split the content of the variable image and insert _thumbs into it to get something like image_thumbs.jpg.

How do i go about this? Many Thanks.

Upvotes: 0

Views: 67

Answers (4)

Chris Fulstow
Chris Fulstow

Reputation: 41872

function addSuffix(filename, suffix)
{
    var pos = filename.lastIndexOf(".");
    var left = filename.substring(0, pos);
    var right = filename.substring(pos);
    var result = left + suffix + right;
    return result;
}

var image = "image.jpg";
var imageWithSuffix = addSuffix(image, "_thumbs");
// imageWithSuffix === "image_thumbs.jpg"

Or, just for fun, a much less readable but shorter solution using a regex:

function addSuffix2(filename, suffix)
{
    return filename.replace(/\.[^\.]+$/, suffix + "$&"); 
}

Upvotes: 4

Yaakov Shoham
Yaakov Shoham

Reputation: 10548

If the file name can contain multiple dots, you need to take the last of it. You can use Regex to do it:

var image = "image.jpg";
image = image.replace(/\.(?!.*\.)/, "_thumbs.");

Upvotes: 0

Wasim Karani
Wasim Karani

Reputation: 8886

Here is the solution

Way 1

var image = "image.jpg";
var splitVar = image.split(".");
alert(splitVar[0]);
alert(splitVar[1]);
alert(splitVar[0]+"_thumbs."+splitVar[1]);

Way 2

alert(image.replace(".","_thumbs."))

http://jsfiddle.net/LqpL3/1/

Upvotes: 1

bozdoz
bozdoz

Reputation: 12860

var image = "image.jpg";
image = image.replace(".","_thumbs.");

Upvotes: 1

Related Questions