user2755667
user2755667

Reputation:

What is the opposite of indexOf?

What would be the opposite of .indexOf()? I used a regexp to find numbers in a string and now I want to add them together:

function getnum(str){
    var nums= str.match(/\d+/g);
    return //30+83//
 }
 getnum("sdsoi30adsd83")

Is there some sort of .charAt() equivalent for arrays I could use for this?

I'm sorry this is a very beginner question. I've been up all day coding and I realize the answer may be very obvious but I've looked all over devdocs.io to no luck.

Upvotes: 2

Views: 5998

Answers (4)

leesei
leesei

Reputation: 6070

You could also use ES5 map-reduce function for this problem.
Of course the for-loop solution works fine.

function getnum(str){
    var nums= str.match(/\d+/g);
    console.log(nums);
    return nums.map(function (str) {
        // convert to a Int array
        return parseInt(str);
    }).reduce(function (prev, curr) {
        return prev+curr;
    }, 0);
}
console.log('result=' +  getnum("sdsoi30adsd83"));

As to your original question, the opposite of indexOf() is indexing by . or [].

var a = "sdsoi30adsd83";
a[a.indexOf('3')]; // = "3"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods

Upvotes: 0

Phil
Phil

Reputation: 164980

return nums.reduce(function(c, n) {
    return c + parseInt(n);
}, 0);

Demo here - http://jsfiddle.net/TyV3s/

Upvotes: 0

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8411

function getnum(str){
    var nums= str.match(/\d+/g);
    var total=0;
    for(var i=0;i<nums.length;i++)
    {
        total+=Number(nums[i]);
    }
    return total;
 }
 getnum("sdsoi30adsd83");

Upvotes: 5

Amir Hoseinian
Amir Hoseinian

Reputation: 2352

For example char at 5th character is

"sdsoi30adsd83"[4] 

which is "i"

Upvotes: 0

Related Questions