Frank1811
Frank1811

Reputation: 61

Remove text before first comma

I have the following text:

Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra

And I only want to show the text after the first ,

Result:

Garden, PFO, Inv 2123, DG, Lot 5543, Ra

How can I do this with Javascript?

Upvotes: 4

Views: 4862

Answers (8)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

    var str = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
    var arr = str.split(',');
    arr.splice(0, 1);
    console.log(arr.join(','));

The procedure is simple. Just first split the string with comma(,) and it returns an array. Then splice the first index of the array by arr.splice(0,1), Here 0 is the index number and 1 for how many elements you want to remove. Finally join the array with comma(,).

Upvotes: 1

Alexander
Alexander

Reputation: 809

var text = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
console.log(text.replace(/^[^,]+, */, ''));

Upvotes: 3

Thomas
Thomas

Reputation: 1140

Solution with regular expression :

let input = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";

let res = /,(.*\w+)/.exec(input)[1];
console.log(res)

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can try this mate

let str = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";

let op = str.replace(/^\w+,/, '');
console.log(op)

Note:- str.replace(/^\w+,/, '').trim() in case you want to remove leading and trialling spaces.

P.S - All the other answers are also right. I just wanted to share one more way of doing it. :)

Upvotes: 2

iLyas
iLyas

Reputation: 1092

You can do something like that :

var text = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
console.log(text.substring(text.indexOf(',')+1).trim());

Note that trim() function removes whitespace from both sides of the string.

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

Split string by , delimiter and remove first item of array using Array.slice() and then join array.

var str = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
var newStr = str.split(", ").slice(1).join(", ");
console.log(newStr);

Also you can find index of first , and get all string after it using String.slice().

var str = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
var newStr = str.slice(str.indexOf(',')+1).trim();
console.log(newStr);

Upvotes: 10

Camille
Camille

Reputation: 2531

@Mohammed answer is a good way. An other one is to get first coma and remove text before.

var str = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
var newStr = str.substring(str.indexOf(',') + 1).trim();
console.log(newStr);

Upvotes: 1

Beri
Beri

Reputation: 11610

In the simplest way:

let input = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
let index = input.indexOf(','); // find the index of first ,
let result = index>-1? input.substring(index+1): input;

You can also add trim(), to remove unwanted white spaces.

Upvotes: 5

Related Questions