mactwoex
mactwoex

Reputation: 1

Double Spaces in Javascript

This code should show an alert box if there are no double spaces but it's not doing that.

var str = prompt("Enter Some Text");
var numChars = str.length;
for (var i = 0; i < numChars; i++) {
    if (str.slice(i, i + 2) === " ") {
        alert("No double spaces!");
        break;
    }
}

alert will pop out if no double spaces

Upvotes: 0

Views: 895

Answers (4)

ThS
ThS

Reputation: 4783

a simple regular expression can do it :

const str = prompt("Enter Some Text");
!/\s\s/.test(str) && alert('No double spaces found !');

Upvotes: 1

Moshe Fortgang
Moshe Fortgang

Reputation: 1125

you need change this line

if (str.slice(i, i + 2) === " ") {

with

if (str.slice(i, i + 2) === "  ") {

Upvotes: 0

briosheje
briosheje

Reputation: 7436

If you want to keep that with the for approach, you should invert the logic and check whether the double whitespace occurs:

var str = prompt("Enter Some Text");
var numChars = str.length;

var doubleWhitespace = false;
for (var i = 0; i < numChars; i++) {
  // get the current and next character.
  var [curr, next] = [str[i], str[i + 1]];
  // if both exists and current is the same as next and both the characters are spaces
  if (curr && next && curr === next && curr === ' ') {
    // double white space.
    doubleWhitespace = true;
    break;
  }
}

if (doubleWhitespace) alert('There is a double space!');
else alert('NO double space');

However, there is a slightly easier solution by just using indexOf:

var str = prompt("Enter Some Text");
if (str.indexOf('  ') > -1) alert("There are double spaces!");
else alert("There are no double spaces!");

Upvotes: 0

OliverRadini
OliverRadini

Reputation: 6467

You could make this a little simpler with an indexOf check:

var str = prompt("Enter Some Text");
if (str.indexOf("  ") === -1) {
  alert("No double spaces!");
}

Upvotes: 1

Related Questions