Reputation: 33
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
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
Reputation: 108500
Use regexp or arrays, something like:
[].splice.call(word = word.split('/'), -1, 1, 'replacement');
word = word.join('/');
Upvotes: 0
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).
Upvotes: 1
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
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
Reputation: 20178
Try using regexp:
"www.abc/def/ghf/ijk/default.aspx".replace(/\/[^\/]+$/, "/replacement");
Upvotes: 8