Reputation: 339
Just trying to do real simple thing - as a variable I get a string which I want to alter. html
<div id="body" class="abc cde fgh xxx-23">text</div>
jquery
if ($("#body").hasClass("cde")) {
var clasa = $('#body').attr('class').match(/\bxxx-.+?\b/);
var arr = clasa.replace('xxx', '');
alert(arr);
}
Alert gives me nothing. I only want to show the number. What I am doing wrong? .attr should return string no? Thank you for help.
Upvotes: 1
Views: 65
Reputation: 1185
You made mistake in your match()
if you want to read only numbers from that String then use
$(document).ready(function(){
var clasa = $('#body').attr('class').match(/[0-9]+$/);
alert(clasa);
var arr = clasa.replace('xxx', '');
alert(arr);
});
and if you want to read whole number xxx-23 then use following
$(document).ready(function(){
var clasa = $('#body').attr('class').match(/xxx-[0-9]+$/);
alert(clasa);
var arr = clasa.replace('xxx', '');
alert(arr);
});
Upvotes: 0
Reputation: 559
Try with below code.
if ($("#body").hasClass("cde")) {
var clasa = $('#body').attr('class').match(/\bxxx-.+?\b/);
var arr = clasa[0].replace('xxx', '');
alert(arr);
}
Upvotes: 0
Reputation: 388446
You can use a regex group like
if ($("#body").hasClass("cde")) {
var value = $('#body').attr('class').match(/\bxxx-(\d+)\b/)[1];
alert(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body" class="abc cde fgh xxx-23">text</div>
Upvotes: 1