1

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.

1
  • 1
    var arr = clasa[0].replace('xxx', ''); Commented Sep 29, 2015 at 9:53

3 Answers 3

1

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>

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

Comments

0

Try with below code.

if ($("#body").hasClass("cde")) {
    var clasa = $('#body').attr('class').match(/\bxxx-.+?\b/);
    var arr = clasa[0].replace('xxx', '');
    alert(arr);
}

Comments

0

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

});

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.