1

I tried the following code but is doesn't work triggers an error:

val.reverse is not a function

How can I fix it?

Demo: http://jsfiddle.net/9ysZa/

//I want this output: 1,455,000
function num(val){
         var result = val.reverse().join("")
                          .match(/[0-9]{1,3}/g).join(",")
                          .match(/./g).reverse().join("");
    return result     
}
alert(num('1455000'))
1

1 Answer 1

3

DEMO

reverse is a method on Array.prototype—it works with arrays. Since val is a string, you'll need to call val.split('') to get it into an array.

function num(val){
         var result = val.split('').reverse().join("")
                          .match(/[0-9]{1,3}/g).join(",")
                          .match(/./g).reverse().join("");
    return result     
}
alert(num('1455000'));

Which alerts the results you're looking for.

EDIT

Based on your comment, it looks like you want to run this on the number 1455000 rather than the string '1455000'. If so, adding a toString call before split() will work (and will work on both strings **and numbers).

Here's an updated fiddle

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

3 Comments

I get in myself code this error: Uncaught TypeError: Object 1455000 has no method 'split' how is fix it?
Add a toString() for safety: var result = val.toString().split("").reverse().join("").match(/[0-9]{1,3}/g).join(",").split("").reverse().join("");
@JulianD. - yep - was typing that as you wrote you comment.

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.