0

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'

3 Answers 3

3

You can use split API.

var hashStr = 'modal-123456'
var splitStr = hashStr.split('-');
console.log(splitStr[0])
console.log(splitStr[1])
Sign up to request clarification or add additional context in comments.

Comments

3

Just use split.

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

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

2 Comments

this will work only in destructuring support js engines.
Yes. However, destructuring is now supported by chrome, firefox, edge, safari and nodejs. It is not supported by IE though. But this is a detail of the solution. You can easily use array indexes if you need to support old browsers. You can also use babel because it rocks.
1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.