0

How can I take a string and split it at a special character into two new variables (and remove the special chars) with javascript?

For example take:

var X = Peggy Sue - Teacher

and turn it into:

varnew1 = Peggy Sue

varnew2 = Teacher

I guess it should also include a condition... if the string has a "-" then do this.

user2864740
  • 60,010
  • 15
  • 145
  • 220

2 Answers2

1

.split is probably what you want. Here is a very simple example

JSFiddle Link

var string = 'Peggy Sue - Teacher'

var new1 = string.split('-')[0].trim();
var new2 = string.split('-')[1].trim();

console.log(new1); // "Peggy Sue"
console.log(new2); // "Teacher"

And if you want to place a simple condition on it looking for - you can do so with the following

var string = 'Peggy Sue - Teacher'

var new1 =  string.indexOf('-') !== -1 ? string.split('-')[0].trim() : string
var new2 = string.indexOf('-') !== -1 ? string.split('-')[1].trim() : string

Second Fiddle

scniro
  • 16,844
  • 8
  • 62
  • 106
0

var result = str.split("-");

will give you an array with 2 members,

result[0] = Peggy Sue result[1] = Teacher

Nicholas Tsaoucis
  • 1,381
  • 2
  • 17
  • 39