Domnick
Domnick

Reputation: 519

Extract text between two words from entire string JavaScript

I have a string where I want to extract all the words that is between two text, such that:

var str="This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed";

var ext = str.split('want').pop().split('!,').shift(); 
alert(ext);

But this gives only +2143334. What I want is all three matching i.e:

+2143334, +234343443, +76645

How can it be done?

Upvotes: 1

Views: 3708

Answers (5)

Michał Momot
Michał Momot

Reputation: 11

My suggestion:

var reg = /(?<=want\s)[a-zA-Z0-9+]+(?=\s\!)/g;
var yourText = 'This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed';
var resultArray = yourText.match(reg);
console.log(resultArray);

Where

want\s

(\s is for space) is text before your match, and

\s\!

if for text after your match.

Best regards ;)

Upvotes: 1

Caiuby Freitas
Caiuby Freitas

Reputation: 289

Actually your code is giving +76645 as result. Anyway, the more straigthforward way to do it is as follows:

var str="This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed";

// To extract numbers only
var vetStrings = str.match(/\d+/g);
console.log(vetStrings);

// To cast the result as numbers
var vetNumbers = vetStrings.map(Number);
console.log(vetNumbers);

:)

Upvotes: 1

Saikat Hajra
Saikat Hajra

Reputation: 680

You can use this one

  str.match(/want\s[a-zA-Z0-9+!@#$%^&*()_+={}|\\]+\s!/g).map((e)=>e.split(' ')[1])

Upvotes: 0

Zenoo
Zenoo

Reputation: 12880

You can use the RegExp (?<=want )([^ ]*)(?= !) :

(?<=want ) makes sure want[space] is behind your expression

([^ ]*) matches anything but a space

(?= !) makes sure [space]! is after your expression

The g is added to make the RegEx global.

var str = "This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed";

console.log(str.match(/(?<=want )([^ ]*)(?= !)/g));

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

You may use the following regex to capture the + followed with 1+ digits after want:

 /want\s*(\+\d+)/g

See the regex demo.

Here, want matches a literal substring, then \s* matches 0+ whitespace chars and the (\+\d+) captures into Group 1 a plus sign and then 1+ digits.

In Chrome, you may even use str.match(/(?<=want\s*)\+\d+/g), but not all browsers already support the ECMAScript 2018 cool regex features.

enter image description here

JS demo:

var str="This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed";
var m,results = [];
var rx = /want\s*(\+\d+)/g;
while(m=rx.exec(str)) {
  results.push(m[1]);
}
console.log(results);

Upvotes: 6

Related Questions