用最后一个逗号分隔字符串

时间:2013-08-15 08:38:01

标签: jquery string

我在jQuery中有字符串。

var s = "Text1, Text2, Text,true";

我需要将这个变量拆分为两部分:

var s1 = substring(...); //after this s1="Text1, Text2, Text"
var s2 = substring(...); //after this s2="true"

你能帮我拆分变量吗?

5 个答案:

答案 0 :(得分:10)

var s="Text1, Text2, Text,true";
var lastIndex = s.lastIndexOf(",")

var s1 = s.substring(0, lastIndex); //after this s1="Text1, Text2, Text"
var s2 = s.substring(lastIndex + 1); //after this s2="true"

答案 1 :(得分:2)

答案 2 :(得分:2)

var index = s.lastIndexOf(",");
var first = str.substr(0, index );
var last = str.substr(index + 1);

或使用slice

var first = str.slice(0, index);
var last = str.slice(index +1);

答案 3 :(得分:1)

尝试

var array = s.match(/(.*),(.*)/);
var s1 = array[1];
var s2 = array[2]

答案 4 :(得分:0)

var s = "Text1, Text2, Text,true";
var n = s.lastIndexOf(",");

var s1 = s.substring(0, n);
var s2 = s.substring(n + 1);

http://jsfiddle.net/Y6yjr/