How can I check if a string is starting with a dot '.
' and also have ':
' in any other position?
Hoped that ^[.][:]*
should achieve that, but looks like not.
CodePudding user response:
You may use:
/^\..*:/s
Sample script:
console.log(/^\..*:/s.test('.abc:def')); // true
console.log(/^\..*:/s.test('abc:def')); // false
CodePudding user response:
The ^[.][:]*
pattern matches a dot at the start of the string and then zero or more colons.
You need to allow any chars other than a :
between the .
and :
:
/^\.[^:]*:/
It will match
^
- start of string\.
- a dot[^:]*
- any zero or more chars other than a:
:
- a colon.
See the regex demo.
JavaScript demo:
const texts = ['.abc\ndef:', '.abc'];
const re = /^\.[^:]*:/;
for (const text of texts) {
console.log(text, '=>', re.test(text))
}
CodePudding user response:
You might also write the check without a regex usin startsWith and includes:
const check = s => s.startsWith(".") && s.includes(":");
[
".abc:def",
"abc:def",
":.",
"."
].forEach(s =>
console.log(check(s))
);