Sougata Mukherjee
Sougata Mukherjee

Reputation: 603

string containing white space or not in react

If the string contains white space alert should be unsuccessful and if string contain no white space alert should be successful

import React from "react";

export default function DropDown() {
let i=document.getElementById("input")?.value;
const submit=()=>{
  var whiteSpaceExp = /^s+$/g;
  if (whiteSpaceExp.test(i))
  {
  alert('unsuccess');
  }
  else
  {
    alert('success');
  }
  }
return (
    <>
      <form>
        <input type="text" id="input"  autoComplete="off" />
        <button onClick={submit}> click  </button>
      </form>
    </>
  );
}

Upvotes: 0

Views: 978

Answers (1)

Dhaval Samani
Dhaval Samani

Reputation: 277

You can simply use the indexOf method on the input string:

function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

Or you can use the test method, on a simple RegEx:

function hasWhiteSpace(s) {
  return /\s/g.test(s);
}

This will also check for other white space characters like Tab.

Upvotes: 2

Related Questions