Languages
[Edit]
EN

JavaScript - get substring between quotes

0 points
Created by:
Cassia-Mendoza
415

In this article, we would like to show you how to get substring between quotes in JavaScript.

Quick solution:

const matches = text.match(/"(.*?)"/g);  // array of substrings surrounded with ""

 

1. Get multiple elements using match() with regex

In this example, we use match() method with /"(.*?)"/g regex, which matches everything in between quotation marks (""). This way we get an array of substrings as a result.

// ONLINE-RUNNER:browser;

const text = 'Example words: "ABC" and "DEF".';

const matches = text.match(/"(.*?)"/g);

if (matches) {
	for (let i = 0; i < matches.length; ++i) {
		const match = matches[i];
      	const substring = match.substring(1, match.length - 1);  // quotation mark removing
		console.log(substring);  
	}
}

Note:

If you remove the global flag (/g) from the regex, you will receive only the first substring as a result.

References

  1. String.prototype.split() - JavaScript | MDN
  2. String.prototype.match() - 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