1

How to check that array values all are HTML files? If the array is not entirely strings ending in .html, I want to show an alert message and stop it. How can I do it?

https://jsfiddle.net/p57cjk81/2/

var arr = ["power.html", "sugar.html", "time.html", "kavi.html", "images.html"];
//var arr=["power.txt", "sugar.html", "time.html", "kavi.html", "images.html"];

var flag = true;

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

  if (arr[i].split(.) == ".html"){
    flag = true;
  } else {
    flag = false;
  }

}

if (flag) {
  alert("Yes all the file have html");
} else {
  alert("All file are not html");  
}

3 Answers 3

2

You can use Array#every and a regex which matches strings with some content ending in .html using the $ end-of-line anchor:

const arr = ["power.html", "sugar.html", "time.html", "kavi.html", "images.html"];

console.log(arr.every(e => /.+\.html$/.test(e)));

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

1 Comment

Nice. I immediately thought of some and you of the opposite :)
1

Try Array#some

const allHtml = (arr) => 
  !arr.some(
    f => { let parts = f.split("."); return parts.length!=2 || parts[1] !== "html"}
  );

let arr1=["power.html","sugar.html","time.html","kavi.html","images.html"];
let arr2=["power.html","sugar.jpg","time.html","kavi.html","images.html"];

console.log(
  allHtml(arr1),   
  allHtml(arr2)
);
  
// suggested usage:

var msg = allHtml(arr1) ? "Yes":"Not";
msg += " all the files have html extension in array";
alert(msg);

1 Comment

Change if (flag) to if (allHtml(arr))
0

Something like this

var arr=["power.html","sugar.html","time.html","kavi.html","images.html"];

if(arr.every(e => /\.html$/.test(e))){
  alert("Yes all the file have html");
}
else{
  alert("All file are not html");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.