Returning value is incorrect, showing as 100 instead

I am currently looping through an array and inspecting each value. Depending on certain conditions, I am moving the value to another array. However, in this case, I am focused on counting the number of periods in each item of the array.

Below is the snippet of code I am working with:

for(i = 0; i < (sortarray.length) -1; i++)
 {
  var count = (sortarray[i].match(/./g)||[]).length;
  console.log(count + ' periods found in name' + sortarray[i]);
  if (count > 1)
  {
   alert('Error: One or more filenames contain periods.');
   return;
  }
  else ...

File names typically have one period, while folder names do not have any. If a value contains more than 1 period, an alert message should be displayed. Despite seeming straightforward, my variable is unexpectedly returning 100 instead of 1, resulting in the alert box always appearing.

Is there a more effective method to count the dots in each value of the array?

Answer №1

Your regex is causing the issue here. The use of the dot (.) in regex matches any character, and with the global option g, it will match the entire string.

This explains why you are seeing a result of 100: length is being applied to the whole string.

To fix this, make sure to escape the dot so that it specifically looks for periods instead of any character.

sortarray[i].match(/\./g)

Answer №2

Instead of using that logic, you can simply check if the first index of . is different from the last index of .. If they are not equal, it means the filename contains more than one ..

for(let i = 0; i < (sortarray.length) -1; i++) {
    if (sortarray[i].indexOf(".") != sortarray[i].lastIndexOf(".")) {
        alert('Error: One or more filenames contain periods.');
        return;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding tween.js seems to have caused the button click event to stop triggering

After adding the code line to tween my display box, the click event is no longer triggered. There are no errors in the console. How can I resolve this issue and what might have caused it? createjs.Tween.get(directionsbox, { loop: false }).to({ x:800, y: ...

Generating documents in Word or PDF format using PHP and Angular data

My goal is to generate a Word document using PHP for which I found a solution involving the use of headers. header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=output.doc"); Initially, this method worked well ...

What is the best approach for utilizing the map function to render JSON data within a JavaScript function in ReactJS?

Currently, I am utilizing the material-ui library to generate card-like items. The list of these items is stored in a JavaScript file as shown below: var Items = [ { name: "Tandoori Pizza", image: "Images/pizza.png", price ...

What steps should I take to resolve the issue of 'this.reduce() not being a function'?

Here is my code : app.get("/", (req, res) => { const reducer = (acc, guildCount) => acc + guildCount; const results = client.shard.fetchClientValues('guilds.cache.size'); console.log(results) let guildCount ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

What is the process for incorporating a Bootstrap link into a specific ReactJS file?

In my current project using React JS, I found the need to incorporate Bootstrap in certain pages. To do this, I initially placed the following code snippet in the Public folder within index.html: <link rel="stylesheet" href="https://netdna.bootstrapc ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

Prevent the ability to Cut, Copy, and Paste in a textbox with AngularJs

Is there a way to prevent copying and pasting in a textarea using AngularJS? I attempted to do this with ng-paste, as shown below: Controller: angular.module('inputExample', []) .controller('ExampleController', ['$scope', ...

What is the best way to implement JavaScript code that can modify the layout of a website across all its pages?

I am facing an issue on my website where, on the index page, clicking a button changes the background color to black. However, this change is not reflected on other pages even though I have linked the JavaScript file to all HTML documents. How can I make i ...

React destructuring props in a dynamic way

Consider we have a props, an incredibly large object: { "firstname": "John", "lastname": "Doe", "age": 11, "mode: "expert", "website": "stackoverflow.com" "pro ...

Discover the occurrences and placements of words within sentences

I am looking to analyze the position and frequency of words in sentences. For example: She went to the store before heading to the park and ended up buying three ice cream cones. From this sentence, the results would be: She -> 1 -> position: 1 went ...

Turning Geometries into Clickable Hyperlinks in Three.js with WebGl Renderer

Recently, I've been experimenting with creating a spherical 360 panorama using three.js. My goal is to incorporate clickable objects that act as hyperlinks. Despite my efforts and research on raycasting, I haven't been successful in making the ob ...

Selecting a JSON object at random

My data is stored in JSON format. [ ["Apple","A"], ["Orange","O"], ["Grape","G"], ["Kiwi","K"] ] Is there a way to randomly select an array item from this data (e.g. ["Grape","G"])? var letterNum = ""; $.ajax ( { url:"getletter.json" }).done( ...

Display arrays in a list layout using React

I'm struggling with displaying some specific data. The structure of the data is shown below: View Data Structure In each object within the array, there are keys such as matchday, awayTeam, homeTeam, and result. All keys except for matchday have an a ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

How can jQuery determine the amount of line breaks within a div element?

My div wrap size is a percentage of the screen width, containing multiple .item divs that break into new lines as the window size decreases. I attempted to calculate the total number of boxes that could fit based on their widths compared to the container ...

Java Code for Upper Triangular Matrix

I have a specific problem with my code that is related to matrix manipulation using Java rs = [51,88,93,89,91,26,51,47,47,31,67,68,46,92,39] The size of the matrix I'm working with is 5X5 and I am aiming to transform it into an upper triangular mat ...

Make sure to load the HTML content before requesting any input from the user through the prompt function

Could you please help me with a question? I'm looking to load HTML content before prompting the user for input using JavaScript's prompt() function. However, currently the HTML is only loaded after exiting the prompt. Below is the code that I hav ...

Retrieving a post variable within a function

In my current scenario, I am trying to pass a variable inside a function. The following code provides more context: <?php $id=$_POST['id']; echo " <script type=\"text/javascript\"> $(document).ready(function(){ ...

Is it possible to modify the inactive color of just one radio button in Framework7?

Is there a way to change the inactive color of only one radio button in Framework7? I am aware that using the CSS variable --f7-radio-inactive-color allows me to set the inactive color for all radio buttons. However, I specifically want to modify the inac ...