1

I am trying to check for each instance of all array-items in a string. Example;

var string = "aa bb ccc";
var array = ["a", "b", "c"];

This should execute my code 7 times - once for each instance of any array-item being in the string. This is quite hard to explain, but I hope the example is enough.

Another explained-code example;

$.each(ArrayItem in string) {
    //execute code
}

I cannot get my head around this one, and haven't yet found anything that remotely works the way I want it to.

Edit

I want to use this to add a price for each letter - say "a,b,c,d,e,f,g" costs $1, while the rest costs $2 - I would need to check for each instance of the array-items above in my string, and calculate the price.

5
  • string is your input and you need array ? Commented Mar 16, 2017 at 12:49
  • Did you try looking at REGEX? That would be 1000 times faster than what you are trying to do. Commented Mar 16, 2017 at 12:49
  • Yes, @Weedoze, the string is the input field and the array contains the items I want to check for. Commented Mar 16, 2017 at 12:51
  • what do you do with space? does it count? for some value? Commented Mar 16, 2017 at 13:13
  • No, it does not Commented Mar 16, 2017 at 13:14

6 Answers 6

2

You can use while+exec inside of for-loop over array items:

var string = "aa bb ass ccc ass"
var array = ["ass", "b", "c"]

var m

array.forEach(function(item) {
  var reg = RegExp(item, 'g')
  while ((m = reg.exec(string)) !== null) {
    console.log('match', m[0])
  }
})

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

3 Comments

Yep it's much better indeed. +1
What if you had a in the array as well?
@evolutionxbox Then a from array will also be counted in ass from string. It's not clear what is the behavior OP expects in such case.
1

Split your string using spread operator and iterate over it to check if array contains any of the elements from that array.

var string = "aa bb ccc";
var array = ["a", "b", "c"];

[...string].forEach(v => array.some(function(c){
  if (c == v) {
    console.log('code executed');
  }
}));

7 Comments

You can also try v=>array.includes(v) && process(v)
Nope, not reliable. You assumed that string consists of charactes, but OP meant "strings".
@dfsq Can you provide me some counter example?
For example: var string = "ass bb ccc"; var array = ["ass", "b", "c"]; there should be 6 code invocations, but your version will yield only 5 because ass will not be found.
@dfsq Hold on will look at it.
|
0

This function will do your work

    function checkString(a){
    for(i=0;i<a.length;i++)
        {  
          if(a[i]!==" "){
            if (yourArray.indexOf(a[i]) > -1) {
                //this line executes 7 times if the string a has 7 characters;
            } 
            }
        }

    }

Comments

0

You have to split the string by ' ' to get an array of substrings, and then use forEach or $.each to loop throught them like:

Spliting:

var strings = string.split(' ');

or more effectivelly:

var strings = string.trim()         // remove sorrounding spaces
                    .split(/\s+/);  // split by any number of spaces

Looping using forEach:

strings.forEach(function(str) {
    // use str
});

Looping using $.each:

$.each(strings, function(i, str) {
    // use str
});

Comments

0

Use split method with " " parameter. https://www.w3schools.com/jsref/jsref_split.asp

var string = "aa bb ccc",
    array = string.split(" ");

Or you can also used lodash: https://lodash.com/docs/4.17.4#split

Comments

0

You could use an object and count the appearances of the letters. Later, you could separate by different priced values.

var string = "aa bb ccc xyz",
    array = ["a", "b", "c"],
    count = Object.create(null);

string.split('').forEach(function (a) {
    if (a !== ' ') {
        count[a] = (count[a] || 0) + 1;
    }
});

Object.keys(count).forEach(function (k) {
    if (array.indexOf(k) !== -1) {
        console.log('found ' + k + ' of array: ' + count[k] + ' times');
    } else {
        console.log('found ' + k + ': ' + count[k] + ' times');
    }
});

7 Comments

I don't think you are answering what OP asked.
could be, who knows.
No, and the code snippet also only output one console log.
@iversen, please add some more examples and the wanted output.
Gotcha, @NinaScholz adding them now
|

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.