检查字符串是否以标点符号开头(JavaScript) [英] Check if string begins with punctuation (Javascript)

查看:298
本文介绍了检查字符串是否以标点符号开头(JavaScript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Javascript检查我的数据字符串是否以标点符号开头?我查看了检查字符串是否为标点符号如何知道字符串开始/以jQuery中的特定字符串结尾?,还有许多其他字符串,但是我无法确定我要去哪里.

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')};

我只得到'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 = ".,:;?!"

检查字符串是否为标点符号,但Chrome和Firefox都给我错误消息(分别为未捕获的语法错误:意外的标识符"和"SyntaxError:缺少;语句前").似乎该错误通常是因为用Javascript写多行字符串,我认为我没有这样做. d.endContext将打印多行字符串,但是当我仅传递."时它可以正常工作,所以我认为这不是问题.

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.

推荐答案

使用正则表达式要简单得多.

using Regex is much simpler.

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

    console.log(result)

  • /表示正则表达式的开始/结束

    • / indicates start/end of Regular expression

      ^的意思是开始于"

      []表示字符集".它将匹配[]

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

      此外,该应用程序对于学习正则表达式非常有用! http://regexr.com/

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

      祝您有美好的一天! :D

      Have a nice day! :D

      这篇关于检查字符串是否以标点符号开头(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆