westcoast_509 westcoast_509 - 5 months ago 67
Javascript Question

Check if string begins with punctuation (Javascript)

How can I check if my data string begins with a punctuation mark using Javascript? I looked at Check if string is a punctuation character and How to know that a string starts/ends with a specific string in jQuery? and a number of others, but I can't tell where I'm going wrong.

Here's a snippet of what I have so far:

var punctuations = [".", ",", ":", "!", "?"];

if (d.endContext.startsWith(punctuations)) {console.log(d.endContext)
} else {console.log('false')};


I only get 'false' returns, but if I pass in "." in

if(d.endContext.startsWith('.'))
...


I get correct results. I also tried

String punctuations = ".,:;?!"


like Check if string is a punctuation character suggested, but both Chrome and Firefox gave me error messages ("Uncaught Syntax Error: Unexpected Identifier" and "SyntaxError: missing ; before statement", respectively). It seemed like that error was usually for writing multiline strings in Javascript, which I don't think I'm trying to do. d.endContext will print multi-line strings, but it works fine when I just pass ".", so I don't think that's the issue.

Answer

using Regex is much simpler.

    var str = '.abc'
    var result = !!str.match(/^[.,:!?]/)

    console.log(result)
  • / indicates start/end of Regular expression

  • ^ means 'start with'

  • [] means 'character set'. it will match any characters between [ and ]

Additionally, this app is quite good to learn Regex! http://regexr.com/

Have a nice day! :D