-5

I need a JS expression to match a combination of /* characters

I have this now

/(\b\/*\b)g

but it does not work.

ETA: any string that has /* should match

so...

  • Hello NO MATCH
  • 123 NO MATCH
  • /* HELLo MATCH
  • /*4534534 MATCH
halfer
  • 19,824
  • 17
  • 99
  • 186
sarsnake
  • 26,667
  • 58
  • 180
  • 286

2 Answers2

1

Since you only want to detect if it contains something you don't have to use regex and can just use .includes("/*"):

function fits(str) {
  return str.includes("/*");
}

var test = [
  "Hello NO MATCH",
  "123 NO MATCH",
  "/* HELLo MATCH",
  "/*4534534 MATCH"
];

var result = test.map(str => fits(str));
console.log(result);
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

You might use a positive lookahead and test if the string contains /*?

If so, match any character one or more times .+ from the beginning of the string ^ until the end of the string $

^(?=.*\/\*).+$

Explanation

  • ^ Begin of the string
  • (?= Positive lookahead that asserts what is on the right
    • .*\/\* Match any character zero or more time and then /*
  • ) Close positive lookahead
  • .+ Match any character one or more times
  • $ End of the string

const strings = [
  "Hello NO MATCH",
  "123 NO MATCH",
  "/* HELLo MATCH",
  "/*4534534 MATCH",
  "test(((*/*"
];
let pattern = /^(?=.*\/\*).+$/;

strings.forEach((s) => {
  console.log(s + " ==> " + pattern.test(s));
});

I think you could also use indexOf() to get the index of the first occurence of /*. It will return -1 if the value is not found.

const strings = [
  "Hello NO MATCH",
  "123 NO MATCH",
  "/* HELLo MATCH",
  "/*4534534 MATCH",
  "test(((*/*test",
  "test /",
  "test *",
  "test /*",
  "/*"
];
let pattern = /^(?=.*\/\*).+$/;

strings.forEach((s) => {
  console.log(s + " ==> " + pattern.test(s));
  console.log(s + " ==> " + (s.indexOf("/*") !== -1));
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70