6

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.

Community
  • 1
  • 1
westcoast_509
  • 322
  • 1
  • 4
  • 13

4 Answers4

21

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 ]

  • !! converts what match returns to a boolean. If it returns a match, it is converted to true. If it returns null, it is converted to false.

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

Have a nice day! :D

Rokt33r
  • 466
  • 4
  • 7
5

Use the some and startsWith methods.

 punctuations.some(function(character) {
     return string.startsWith(character)
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

The some() method tests whether some element in the array passes the test implemented by the provided function. Or you can also use regex

/[.,:!?]/.test(string.charAt(0))
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
3

Using Array.prototype.indexOf is probably the simplest:

var punctuations = [".", ",", ":", "!", "?"];
var stringToSearch = d.endContext;  // Your string to search
if (punctuations.indexOf(stringToSearch.charAt(0)) !== -1) {
    // Your awesome code goes here
}

It's compatible to IE9 and pretty much all Chrome and Firefox (down to 1.5) versions but if you are using jQuery, you can use inArray for further backwards compatibility.


Or... just for fun you could go the other end, be cutting edge, and break all non-beta browsers with the new ES7 Array.prototype.includes:

var punctuations = [".", ",", ":", "!", "?"];
var stringToSearch = d.endContext;  // Your string to search
if (punctuations.includes(stringToSearch.charAt(0))) {
    // Your awesome code goes here
}

Compatible with:

  • Chrome 47 (not yet released)
  • Firefox 43 (not yet released)
user193130
  • 8,009
  • 4
  • 36
  • 64
2

Here's a beautiful solution:

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

function isPunkyString(str) {
  return punctuations.indexOf(str[0]) > -1;
}

console.log(punkyString, "is punky:", isPunkyString(punkyString));
console.log(nonPunkyString, "is punky:", isPunkyString(nonPunkyString));

Unit tests!

var punkyStrings = punctuations.map(function (item) {
    return item + " <---<< Punctuations!"
});

var nonPunkyStrings = punctuations.map(function (item, i) {
    return i + " <---<< No punctuations!"
});

punkyStrings.forEach(function (item, i) {
    console.log("Expect", "isPunkyString(\"" + item + "\")", "to be true:", isPunkyString(item));
});

nonPunkyStrings.forEach(function (item, i) {
    console.log("Expect", "isPunkyString(\"" + item + "\")", "to be false:", isPunkyString(item));
});

Why is it beautiful? Because I have used the word punky! :D Oh and I treat the string as an array. Which is nice!

Has anyone else unit tested their code? :D

Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40