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 bee
var word ="www.abc/def/ghf/ijk/**replacement**";
The number of slashes may vary each time.
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 bee
var word ="www.abc/def/ghf/ijk/**replacement**";
The number of slashes may vary each time.
Share Improve this question edited Sep 3, 2012 at 13:45 unkulunkulu 11.9k2 gold badges33 silver badges49 bronze badges asked Sep 3, 2012 at 13:40 karthikkarthik 331 silver badge4 bronze badges 2- array = string.split("/"); array[array.length-1] = newString – Carlo Moretti Commented Sep 3, 2012 at 13:42
-
There are
lastIndexOf
,split
,replace
inString
. – Aleksei Zabrodskii Commented Sep 3, 2012 at 13:43
6 Answers
Reset to default 8Try using regexp:
"www.abc/def/ghf/ijk/default.aspx".replace(/\/[^\/]+$/, "/replacement");
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";
You can array split on '/', then pop the last element off the array, and rejoin.
word = word.split('/');
word.pop();
word = word.join('/') + replacement;
How about the KISS principle?
var word = "www.abc/def/ghf/ijk/default.aspx";
word = word.substring(0, word.lastIndexOf("/")) + "/replacement";
What about using a bination 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
Use regexp or arrays, something like:
[].splice.call(word = word.split('/'), -1, 1, 'replacement');
word = word.join('/');