0

I need to check if the string ft-file is inside my innerHTML variable. It need to be the exact match including the hyphen.

A small aberration shouldn't be a match, for example "ft-file2", should be false, too.

I tried it with a "regex" but I get the wrong result (false). This is the Fiddle and the code.

 let text = document.getElementsByClassName("fulltext")[0].innerHTML;
var reg = /^ft-file$/;

if (reg.test(text) == true) {
    console.log("true");
} else {
    console.log("false")
}
<div class="fulltext">
   [test="data/ft-file/images/small/red"]
</div>
Keroster
  • 23
  • 7
  • `^ft-file$` looks for a **line** that is exactly `ft-file` - your string isn't in a line by itself `/\bft-file\b/` may work - but, beware [Tony the pony, he comes](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Bravo Jun 21 '22 at 00:28
  • @Keroster, added a solution, check if that addresses your question – Naveed Jun 21 '22 at 00:52

3 Answers3

0

Your regular expression is wrapped in ^ and $, which mean start and end of the line, respectively. This means it would only match if that was the only content in innerHTML

Setting your regex to be /ft-file/ will achieve what you are looking for.

See regex tester: https://regex101.com/r/PMVxBp/1

  • Thanks. But it doesn't work as expected. I need the exact match. With your solution `ft-file2` would be a match, too. – Keroster Jun 21 '22 at 00:42
0

it should be as simple as searching as "ft-file" or "(ft-file)" and expecting not digit and non-character before and after. It captures the result as a group

Try this

 [\W\D](ft-file)[\W\D]

https://regex101.com/r/20U1yJ/1

Naveed
  • 11,495
  • 2
  • 14
  • 21
0

Update

A lookbehind (?<=/) and a lookahead (?=\/) matches only if ft-file is followed by a / and is following a /.

You need to escape the hyphen

/(?<=\/)ft\-file(?=\/)/g

The characters that need to be escaped (prefixed with \) are:

-
^
\
]

Regex101

let txt = document.querySelector(".fulltext").innerHTML;
const rgx = /(?<=\/)ft\-file(?=\/)/g;
let match = rgx.test(txt);
console.log(match);
<div class="fulltext">
  [test="data/ft-file/images/small/red"]
</div>
zer00ne
  • 41,936
  • 6
  • 41
  • 68