I want to detect when a string is a quote of some kind. For my use case a string can be classed as a quote if it starts with a quotation mark, which will enable me to mark the string as a quote whilst it is being typed out.
Test cases
✅ "I am a quote
✅ 'I am a quote
✅ “I am a quote
✅ “I am a quote
❌ I am not a quote
❌ This isn't a quote
CodePudding user response:
My solution here is quite simple and checks for strings starting with “"'
:
const getInputTextType = (inputText: string) =>
/^[“"']/.test(inputText.trim()) ? "quote" : "text";
console.log(getInputTextType('"I am a quote"'));
console.log(getInputTextType("'I am a quote"));
console.log(getInputTextType("“I am a quote"));
console.log(getInputTextType(" “I am a quote "));
console.log(getInputTextType("I am not a quote"));
console.log(getInputTextType("This isn't a quote"));
If anyone knows of any instances where a potential quote wouldn't be caught (based on starting with a quotation mark) let me know.
CodePudding user response:
If the only thing to check is the first character, then just compare that first character with includes
against the string of possible quote characters:
const getInputTextType = (inputText) =>
`“"'`.includes(inputText.trim()[0]) ? "quote" : "text";
console.log(getInputTextType('"I am a quote"'));
console.log(getInputTextType("'I am a quote"));
console.log(getInputTextType("“I am a quote"));
console.log(getInputTextType(" “I am a quote "));
console.log(getInputTextType("I am not a quote"));
console.log(getInputTextType("This isn't a quote"));