VinoCoder
VinoCoder

Reputation: 1153

Remove last word after comma in a string jquery

I need to remove last word after comma in a string.

For example, i have string like below

var text = "abc, def, gh";

I want to remove gh in that string

I have tried like below

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

But im getting error

Cannot read property 'split' of undefined

Please help me.

Upvotes: 3

Views: 3517

Answers (6)

Maharoz Alam Mugdho
Maharoz Alam Mugdho

Reputation: 466

Here I use lastIndexOf() and substring() methods. substring() is used to collect the string from Oth index to last empty space.

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

Upvotes: 1

Fisherman
Fisherman

Reputation: 6121

Split return an array, You should slice/pop it cause sub-string is a poperty of a string, or you can use regex as other mentions.

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

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

We can solve this using a regex without a capture group:

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

This regex strategically removes just the final word in the CSV list.

Here is a variation of the above which uses a capture group:

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

Upvotes: 0

Subash
Subash

Reputation: 816

Try this,

var str = "abc, def, gh";

var result = str.substring(0, str.lastIndexOf(","));

alert(result);

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can achieve this using array operations:

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

Or you can do it by string operations:

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

Upvotes: 7

Farhad Bagherlo
Farhad Bagherlo

Reputation: 6699

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

Upvotes: 3

Related Questions