How to split the values in JavaScript - Stack Overflow

I have to split the values using JavaScript and want to find the last occuring slashfrom a string an

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 in String. – Aleksei Zabrodskii Commented Sep 3, 2012 at 13:43
Add a ment  | 

6 Answers 6

Reset to default 8

Try 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('/');

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745084149a4610305.html

相关推荐

  • How to split the values in JavaScript - Stack Overflow

    I have to split the values using JavaScript and want to find the last occuring slashfrom a string an

    1天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信