最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to split the values in JavaScript - Stack Overflow

programmeradmin1浏览0评论

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('/');
发布评论

评论列表(0)

  1. 暂无评论