karthik
karthik

Reputation: 33

How to split the values in JavaScript

I have to split the values using JavaScript and want to find the last occuring slash / from a string and replace the contents after the last slash / For example:

var word = "www.abc/def/ghf/ijk/**default.aspx**";

should become

var word ="www.abc/def/ghf/ijk/**replacement**";

The number of slashes may vary each time.

Upvotes: 0

Views: 301

Answers (6)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

An alternative without regular expression (I just remembered lastIndexOf() method)

var word = "www.abc/def/ghf/ijk/default.aspx";
word = word.substring(0, word.lastIndexOf("/")) + "/replacement";

Upvotes: 5

David Hellsing
David Hellsing

Reputation: 108500

Use regexp or arrays, something like:

[].splice.call(word = word.split('/'), -1, 1, 'replacement');
word = word.join('/');

Upvotes: 0

Lix
Lix

Reputation: 47956

What about using a combination of the join() and split() functions?

var word = "www.abc/def/ghf/ijk/default.aspx";

// split the word using a `/` as a delimiter
wordParts = word.split('/'); 

// replace the last element of the array
wordParts[wordParts.length-1] = 'replacement';

// join the array back to a string.
var finalWord = wordParts.join('/');

The number of slashes doesn't matter here because all that is done is to split the string at every instance of the delimiter (in this case a slash).

Here is a working demo

Upvotes: 1

Derek Hunziker
Derek Hunziker

Reputation: 13141

How about the KISS principle?

var word = "www.abc/def/ghf/ijk/default.aspx";
word = word.substring(0, word.lastIndexOf("/")) + "/replacement";

Upvotes: 1

Ben Taber
Ben Taber

Reputation: 6731

You can array split on '/', then pop the last element off the array, and rejoin.

word = word.split('/');
word.pop();
word = word.join('/') + replacement;

Upvotes: 2

Jasper de Vries
Jasper de Vries

Reputation: 20178

Try using regexp:

"www.abc/def/ghf/ijk/default.aspx".replace(/\/[^\/]+$/, "/replacement");

Upvotes: 8

Related Questions