0

I have a div with certain data attribute. And want to extract certain value from that data attribute.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-space="left-15 right-15">
</div>
<script>
var defaultValue = $('div').attr('data-space').replace('left-15 right-', '') / 5;
console.log(defaultValue);
</script>

here data-space="left-15 right-15" is a dynamic I will change based on user event.

For example when the data-space changed to data-space="left-0 right-0" it will return nan. How can I solve this issue using regex.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-space="left-0 right-0">
</div>
<script>
var defaultValue = $('div').attr('data-space').replace('left-15 right-', '') / 5;
console.log(defaultValue);
</script>

0

1 Answer 1

1

var defaultValue = $('div').attr('data-space').replace(/left-(\d)+\sright-/, '')/5;
	
console.log(defaultValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-space="left-0 right-0">
</div>

Sign up to request clarification or add additional context in comments.

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.