0

How to get element with specific length (ex: length = 7) in array If there's no element with length = 7, I want to print something. If I do inside the loop it will print many times base on number of element.

let txt = `abc klj 1123 MPM SN67990 MKP LJJ`
let arr = txt.split(' ')
console.log(arr)

for (let i = 0; i < arr.length; i++) {

    if (arr[i].length == 7) {
        console.log(arr[i])
    } 
    
    // TODO: if no element with length = 7 in arr
}

2

1 Answer 1

2

Check that .every one of the elements passes the length test.

if (arr.every(subarr => subarr.length !== 7)) {
  // then no array with length 7 exists
}

Another method - use a regular expression to match 7 characters, no array required.

if (!txt.match(/\b\S{7}\b/)) {
  // then no word exactly 7 characters long exists
}
Sign up to request clarification or add additional context in comments.

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.