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



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

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

var text = "abc, def, gh";

我想删除该字符串中的gh

我已经尝试过如下

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

但是我得到错误

无法读取未定义的属性"拆分">

请帮助我。

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

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);

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

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);

var text = "abc, def, gh";
var str=text.replace(/(.*),.*/, "$1");
alert(str);

试试这个,

var str = "abc, def, gh";
var result = str.substring(0, str.lastIndexOf(","));
alert(result);

拆分返回一个数组,您应该切片/弹出它,因为子字符串是字符串的弹出式,或者您可以使用正则表达式作为其他提及。

var text = "abc, def, gh";
var result = text.split(",");
var get = result.slice(0, result.length-1);
// or var get = result.pop();
alert(get);

在这里我使用lastIndexOf()substring()方法。 substring() 用于收集从 Oth 索引到最后一个空白空间的字符串。

<html>
<head>
    <script>
        function myFunction() {
            var str = "abc, def, gh";
            var lastIndex = str.lastIndexOf(" ");
            str = str.substring(0, lastIndex);
            document.getElementById("myText").innerHTML = str;
        }
    </script>
</head>
<body onload="myFunction()">
    <h1>the value of string is now:  <span id="myText"></span></h1>
</body>    

我们可以使用没有捕获组的正则表达式来解决这个问题:

var text = "abc, def, gh";
text = text.replace(/(?=,[^,]*$).*/, "");
console.log(text);

此正则表达式战略性地仅删除 CSV 列表中的最后一个单词。

以下是使用捕获组的上述变体:

text = text.replace(/(.*),.*/, "$1");
console.log(text);