Reputation: 48943
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
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
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
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