'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?
Solution 1:[1]
var text = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
console.log(text.replace(/^[^,]+, */, ''));
Solution 2:[2]
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);
Solution 3:[3]
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.
Solution 4:[4]
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. :)
Solution 5:[5]
@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);
Solution 6:[6]
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.
Solution 7:[7]
Solution with regular expression :
let input = "Kenya, Garden, PFO, Inv 2123, DG, Lot 5543, Ra";
let res = /,(.*\w+)/.exec(input)[1];
console.log(res)
Solution 8:[8]
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(,).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexander |
| Solution 2 | |
| Solution 3 | Beri |
| Solution 4 | |
| Solution 5 | Camille |
| Solution 6 | iLyas |
| Solution 7 | Thomas |
| Solution 8 |
