简体   繁体   English

如何在JavaScript中拆分值

[英]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: 我必须使用JavaScript拆分值,并想从字符串中查找最后一个出现的斜杠/并在最后一个斜杠之后替换内容/例如:

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. 斜杠的数量可能每次都不同。

尝试使用regexp:

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

An alternative without regular expression (I just remembered lastIndexOf() method) 没有正则表达式的替代方法(我只记得lastIndexOf()方法)

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;

What about using a combination of the join() and split() functions? 结合使用join()split()函数呢?

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 这是一个工作演示

How about the KISS principle? KISS原则如何?

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

Use regexp or arrays, something like: 使用正则表达式或数组,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM