我需要用多个分隔符获取拆分数组的最后一个元素。分隔符是逗号和空格。如果没有分隔符,则返回原始字符串。
如果字符串是"how,are you doing, today?"它应该返回"today?"
如果输入是“hello”,输出也应该是“hello”。
如何在JavaScript中做到这一点?
我需要用多个分隔符获取拆分数组的最后一个元素。分隔符是逗号和空格。如果没有分隔符,则返回原始字符串。
如果字符串是"how,are you doing, today?"它应该返回"today?"
如果输入是“hello”,输出也应该是“hello”。
如何在JavaScript中做到这一点?
当前回答
这种方式容易理解,而且非常简短。
const output = input.split(',').pop().split(' ').pop();
其他回答
var title = 'fdfdsg dsgdfh dgdh dsgdh tyu hjuk yjuk uyk hjg fhjg hjj tytutdfsf sdgsdg dsfsdgvf dfgfdhdn dfgilkj,n, jhk jsu wheiu sjldsf dfdsf hfdkdjf dfhdfkd hsfd ,dsfk dfjdf ,yier djsgyi kds';
var shortText = $.trim(title).substring(1000, 150).split(" ").slice(0, -1).join(" ") + "...More >>";
var item = "one,two,three";
var lastItem = item.split(",").pop();
console.log(lastItem); // three
如果你不想构造一个数组……
var str = "how,are you doing, today?";
var res = str.replace(/(.*)([, ])([^, ]*$)/,"$3");
英语的分类如下:
/(anything)(any separator once)(anything that isn't a separator 0 or more times)/
replace表示用最后一个分隔符之后的内容替换整个字符串。
所以你可以看到这是如何应用的。注意原始字符串没有被修改。
史上最好的,也是我最喜欢的分切法
Const STR = "你好,你今天怎么样?" Const last = str.split(' ').slice(-1)[0] console.log ({})
另一个是使用拆分,然后弹出最后一个。
Const STR = "你好,你今天怎么样?" Const last = str.split(' ').pop() console.log ({})
每件事都有一句话。:)
var output = input.split(/[, ]+/).pop();