debarchito
debarchito

Reputation: 1335

How can I get the first and the last word or character between which a special character fall in javascript?

Let's consider an string named calc which is defined as :

const calc = "Find 2&3";

And now a function named parse(), which does something like this :

console.log( parse(calc) );
// => First character is 2 while last character is 3 

So, we observed that the parse() function figured out the first and last character between which the & fall. So, can the parse() be made ? If yes how ? If no any alternative ? What if there are multiples ?

e.g.

const calc = "Find 2&3 , 4&5 , 6&7";
console.log( parse(calc) );
// => First character is 2 while last character is 3 
// => First character is 4 while last character is 5
// =>  First character is 6 while last character is 7 

Upvotes: 1

Views: 41

Answers (1)

Ori Drori
Ori Drori

Reputation: 192262

You can use String.match() with a regular expression to match the 1st character and last character, which are not a space (\S) and have & between them (more info at regex101).

Note: the result of the match is an array that contains the matched string, and the two capture groups results. I use destructuring to assing them to first and last.

const calc = 'Find 2&3';

const [, first, last] = calc.match(/(\S)\S*&\S*(\S)/);

console.log(first, last);

To get all matches you can use String.matchAll() (not supported by IE or Edge). The result would be an iterator, which you can spread to an array containing the sub-arrays with the results.

const calc = 'Find 2&3 , 4&5 , 6&7';

const matches = calc.matchAll(/(\S)\S*&\S*(\S)/g);

console.log([...matches]);

Upvotes: 3

Related Questions