0

Hi i am trying to get just the numbers from a html string and append them to a URL which is then wrote to the page as a example:

<p id="catId">cat number 2301254187</p>
<script type="text/javascript">
        var itemId = document.getElementById('catId').innerHTML;
        var links = '<a href="http://www.test.com' + catId + '">Go to Catergory</a>';
        document.write(links);

Ive tried something like above which works but i get the whole of the contents of the p tag. Im pretty new to this and im guessing that regular expressions need to be used to extract the numbers only?

3 Answers 3

1

You were right about needing to use a regular expression.

<p id="catId">cat number 2301254187</p>
<script type="text/javascript">
    var itemId = document.getElementById('catId').innerHTML.match(/\d+/);

    if (itemId.length) {
        var links = '<a href="http://www.test.com' + itemId[0] + '">Go to Catergory</a>';
        document.write(links);
    }
</script>

See the match() method

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

Comments

1

You can fetch the numbers with a simple regex

var itemId = document.getElementById('catId').innerHTML.match(/\d+/)[0]

Comments

0

not necessarily, should the string always be cat number NNNNNNNN, you can use split.

var itemId = document.getElementById('catId').innerHTML.split(' ')[2];

Which splits the string into an array separated by spaces, and then displays the third element, which would be your number.

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.