简体   繁体   中英

How to extract certain character from data attribute using regex?

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> 

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM