Languages
[Edit]
EN

JavaScript - check if string contains spaces

0 points
Created by:
Wiktor-Sribiew
350

In this article, we would like to show you how to check if string contains spaces in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const text = 'Example text.';

if (text.match(/\s/)) {
	console.log('The string contains space(s).');
}

 

Practical example

In this example, we use match() method to check if the text string contains any spaces.

// ONLINE-RUNNER:browser;

const regex = /\s/;
const text = 'Example text.';

if (text.match(regex)) {
	console.log('The string contains space(s).');
}

Note:

The match() method used with /g flag returns all results matching the complete regular expression (regex). If nothing matches returns null.

Alternative solution

In this section, we use regex.test(text) instead of text.match(regex) to check if the text string contains spaces.

// ONLINE-RUNNER:browser;

const regex = /\s/;
const text = 'Example text.';

if (regex.test(text)) {
	console.log('The string contains space(s).');
}

Note:

The test() method returns true if there is a match between the regex and the text string. Otherwise it returns false.

References

  1. String.prototype.match() - JavaScript | MDN
  2. RegExp.prototype.test() - JavaScript | MDN
Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join