Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

RegEx not matching repeated non-word characters

i have a string which is converted to an array. The string contains non-word characters like -,+ etc. The format for regular expression i am using is let regEx = /\W+/; and suppose this is the string let a = "cat-hat-bat" i am using test function to check for non-word characters in the string which is now converted to an array using split method of array. The problem i am facing is that on encountering same non-word character in the array i get the first non-word character index for both the non-word characters. For ex, if i convert the a variable to an array every alphabet will have an index number and so do the non-word character so what i get in output is 3 index number for both the non-word characters instead of 3 and 7. Please help me with this problem it's urgent.

2 Answers

Steven Parker
Steven Parker
229,732 Points

You didn't explain how you're obtaining the index value, but I'd guess that's where the issue is. To make it possible to provide specific help, show your actual code.

let a = "cat-hat-bat"; let b = a.split("");

let regEx = /\W+/g; let popIn = [ ];

for( let i = 0; i < b.length; i++ ){ if( regEx.test(b[i]) ){
popIn.push(b.indexOf(b[i]));
} }

Steven Parker
Steven Parker
229,732 Points

The "indexOf" function always returns the first match for a specific term, so that's why you get the same value each time.

But since you're looping through the array anyway, you can just push the current index value instead:

for (let i = 0; i < b.length; i++) {
  if (regEx.test(b[i])) {
    popIn.push(i);
  }
}

Thanks for the help the solution worked.

.

Steven Parker
Steven Parker
229,732 Points

This is very different from the original question. This issue should be started as a new question, with a bit more explanation about what problem you are experiencing with it. Specifically, what it is doing that is different from your intentions and expectations. The specific data you are using to test it would also be helpful.

Also, this code is not complete. At the very beginning, it calls a function named "readLine" that is not defined.

.