Skip to content

How to find a word that has surrounded with indicator? javascript

I have a string below which has some identifier to get an specific word on it.

string example: “I will c#hec*k on it”

the “#” indicates starting, and the “*” indicates for last.

I want to get two strings.

  1. check – the whole word that has “#” and “*” on it.
  2. hec – string that was surrounded.

I have started to use the below code, but it seems does not work.

sentence.split('#').pop().split('*')[0];

Somebody knows how to do it. would appreciate it thanks

Answer

var s = "I will c#hec*k on it"
console.log(s.match(/(?<=#)[^*]*(?=*)/))  // this will print ["hec"]
console.log(s.match(/w*#[^*]**w*/).map(s => s.replace(/#(.*)*/, "$1"))) // this will print ["check"]

where:

  • (?<=#) means “preceded by a #
  • [^*]* matches zero or more characters that are not a *
  • (?=*) means “followed by a *
  • w* matches zero or more word characters
  • (.*) is a capturing group (referenced by $1) matching any number of any kind of character (except for newlines)