Given this HTML:
<div id="foo">
<input type=button class="foo abtn_1">
<input type=button class="joe bbtn_2">
<input type=button class="doe cbtn_2">
<input type=button class="joe dbtn_1">
<input type=button class="foo ebtn_2">
</div>
On click, I want to get the first part of the class with the underscore and number.
So from the first input I would be getting: abtn
Currently I use:
$('#foo input').on('click', function () {
var a = $(this).attr('class')
.replace('foo','')
.replace('joe','')
.replace('doe','')
.replace('_1','')
.replace('_2','')
console.log(a);
});
I would imagine there should be a more robust and faster performance-wise way of doing this probably with Regex?
You can use a regular expression to find the right part of the right class name directly without doing any replacements:
Working demo here: http://jsfiddle.net/jfriend00/EDrvJ/
Here’s the regex explained:
The
(^|\s)at the start and the(\s|$)end ensure that we are getting a whole class name match, not just a partial match. The|symbol is OR in regex so we can match either a^or a\swith(^|\s).