JasonDavis
JasonDavis

Reputation: 48943

Separate string into multiple variables with JavaScript

Using JavaScript I want to take a string like this var hashStr = 'modal-123456' and assign the string left of the - to a variable and the string right of the - to another variable.

If the string does not contain a - then ignore it.

How can I best achieve this?

var hashStr = location.hash.replace('#', '');

// hashStr now === 'modal-123456'

var firstHalf = // modal

var secondHalf = // '123456'

Upvotes: 0

Views: 2362

Answers (3)

Quentin Roy
Quentin Roy

Reputation: 7887

Just use split.

var hashStr = 'modal-123456';
var [firstHalf, secondHalf] = hashStr.split("-");

console.log("first half:", firstHalf);
console.log("second half:", secondHalf);

Upvotes: 3

gurvinder372
gurvinder372

Reputation: 68393

Simply

var hashStr = location.hash.replace('#', '');
var firstHalf = hashStr.split("-")[0];
var secondHalf = hashStr.split("-")[1];

or

var hashStr = location.hash.replace('#', '').split("-");
var firstHalf = hashStr[0];
var secondHalf = hashStr[1];

Upvotes: 1

Bkjain655
Bkjain655

Reputation: 200

You can use split API.

var hashStr = 'modal-123456'
var splitStr = hashStr.split('-');
console.log(splitStr[0])
console.log(splitStr[1])

Upvotes: 3

Related Questions