Home > Net >  How to select a word , word start with and including next word
How to select a word , word start with and including next word

Time:10-12

here is the strings:

stop
stop random some company
stopping non stop
arif

I am trying to match stop, stop random, stopping for this I try:

/stop|(stop.\w )/

in this, both this part as stop and (stop.\w ) works separately. but not works combined. any idea?


Sample Code:

const data = [
  "stop",
  "stop random some company",
  "stopping non stop",
  "arif"
]

const regex = /stop|(stop.\w )/

data.forEach((word) => {
  const match = word.match(regex)
  if (match) {
    console.log(match[0])
  }
})

thanks in advance

CodePudding user response:

You can use this regex:

  • Start check with stop
  • If there is a space, check till next word break
  • If there is no space, check till next space
  • Also check if the word is the last word.

const data = [
  "stop",
  "stop random some company",
  "stopping non stop",
  "arif"
]

const regex = /stop([^ ] | [^ ] |$)/

data.forEach((word) => {
  const match = word.match(regex)
  if (match){
    console.log(match[0])
  }
})

CodePudding user response:

[ ]? - Match a space if present

[\w]* - matches any series of word characters

On regex101.

const data = [
  "stop",
  "stop random some company",
  "stopping non stop",
  "arif"
]

const regex = /stop[ ]?[\w]*/

data.forEach((word) => {
  const match = word.match(regex)
  if (match) {
    console.log(match[0])
  }
})

  • Related