-1

I am attempting to take the city out of a city, state string. For instance, "Portland, OR" would need to equal "Portland". How can I use Javascript or a regular expression to do this?

var myString = "Portland, OR";

I want to extract everything up to the comma but not including the comma.

Mjuice
  • 1,288
  • 2
  • 13
  • 32
  • You should provide sample input and desired output for each it would help a lot. – Nicolas Nov 30 '16 at 00:09
  • You might try a regular expression that matches everything from the start of a string that isn't a comma and returns it, or matches everything from the first comma to the end of the string and removes it. – RobG Nov 30 '16 at 00:11
  • 1
    Just use regex [`^[^,]+`](https://regex101.com/r/wn7A6y/4), this is a very simple question, next time use google... – Nicolas Nov 30 '16 at 00:13

2 Answers2

2
var city = "Portland, OR".split(",")[0];

With regex:

var regex = /^[^,]+/;
var city =  regex.exec("Portland, OR");
BrTkCa
  • 4,703
  • 3
  • 24
  • 45
2

This is the regex version

var result = myString.match(/^[^,]+/)

UPDATE

This one always returns a value without error

var result = String(myString || "").match(/^[^,]*/)[0]
Tolgahan Albayrak
  • 3,118
  • 1
  • 25
  • 28