删除字符串 jquery 中逗号后的最后一个单词

Vin*_*der 3 jquery

我需要删除字符串中逗号后的最后一个单词。

例如,我有如下所示的字符串

var text = "abc, def, gh";
Run Code Online (Sandbox Code Playgroud)

我想删除gh该字符串

我试过如下

var text = "abc, def, gh";
var result = text.split(",");
var get = result.substring(-1, result.length);
alert(get);
Run Code Online (Sandbox Code Playgroud)

但我收到错误

无法读取未定义的属性“split”

请帮我。

Ank*_*wal 7

您可以使用数组操作来实现此目的:

var text = "abc, def, gh";
//create the array 
var resArray = text.split(",");
//remove last element from array
var poppedItem = resArray.pop();
//change the final array back to string
var result = resArray.toString();
console.log(result);
Run Code Online (Sandbox Code Playgroud)

或者你可以通过字符串操作来完成:

var text = "abc, def, gh";
//find the last index of comma
var lastCommaIndex = text.lastIndexOf(",");
//take the substring of the original string
var result = text.substr(0,lastCommaIndex);
console.log(result);
Run Code Online (Sandbox Code Playgroud)