0

I have the following string:

apple, banana, orange

and I want to get only the first word of that string and before the first comma:

In this example it's apple

For that, I have done the below:

var string = "apple, banana, orange";
var splitedArray = string.split(',');
console.log('This should show it ', splitedArray[0])

It works fine, but I am wondering if there exists a better way to it.

Hamza L.
  • 1,783
  • 4
  • 25
  • 47

2 Answers2

3

Instead of mapping the entire string into a array, you could just use substring togther with indexOf

var str = "apple, banana, orange";
var firstWord = str.substring(0, str.indexOf(','))

substring will take a part of your string fra indexA to indexB, and indexOf will give you the index of the first occurrence of a pattern (in this case a ,).

I guess this approach would be faster since it does not need loop through the entire string


substring https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring

indexOf https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

TryingToImprove
  • 7,047
  • 4
  • 30
  • 39
  • Clean and neat, but I would like to understand more if you don't mind what's going on exactly also what about if I want to get `banana` with your approach, I believe it wouldn't work.. ? – Hamza L. Jul 26 '17 at 13:59
  • @HamzaL.I have updated the answer. If you want to get the second item you could use the array-way (easy), or implement your own algoritmen for finding what you need (harder). – TryingToImprove Jul 26 '17 at 14:44
1

Yeah, this is how I would've done it, too. For short: string.split(",")[0]

Slava Eremenko
  • 2,235
  • 1
  • 11
  • 9