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 >
[test="data/ft-file/images/small/red"]
</div>
CodePudding user response:
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:
-
^
\
]
let txt = document.querySelector(".fulltext").innerHTML;
const rgx = /(?<=[/])ft\-file(?=[\/])/gm;
let match = rgx.test(txt);
console.log(match);
<div >
[test="data/ft-file/images/small/red"]
</div>
CodePudding user response:
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
CodePudding user response:
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]