munchschair munchschair - 7 months ago 10
Javascript Question

How do I get a regular expression that starts with this phrase?

I want a regular expression that takes phrases inside a larger string that start with "st". It has to be case insensitive and searches through the whole strings and gives me back the number of matches.

What I have:

/st+/ig


I am testing it on

st stuff pistuff stuff
stuff st st st st stuff notstuff
STUFF STUFF STUFF
sti
stiiiiii
stiiii
stufff
stiufff


It matches almost everything correctly, except it is also picks up pistuff and notstuff.

Answer

Updated to capture words that start with st or the two characters st, case-insensitive:

  • For whole word matches: /\bst\w*/ig
  • For matches, without needing to match entire word: /\bst/ig

\b is used to mark a word boundary.

var strArr = [
  'st stuff pistuff stuff',
  'stuff st st st st stuff notstuff',
  'STUFF STUFF STUFF',
  'sti',
  'stiiiiii',
  'stiiii',
  'stufff',
  'stiufff'
];

var re = /\bst\w*/ig;
var count = 0;

strArr.forEach(function(str) {
  count += str.match(re).length;
  document.body.insertAdjacentHTML('beforeend', str.match(re) + '<br>');
});

document.body.insertAdjacentHTML('beforeend', 'count: ' + count);

Also, Regex101

Comments