简体   繁体   English

检查字符串是否以标点符号开头(Javascript)

[英]Check if string begins with punctuation (Javascript)

How can I check if my data string begins with a punctuation mark using Javascript?如何使用 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?我查看了检查字符串是否为标点符号以及如何知道字符串以 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 "."我只得到 'false' 回报,但如果我传入“.” 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).就像检查字符串是否是建议的标点符号一样,但是 Chrome 和 Firefox 都给了我错误消息(分别为“未捕获的语法错误:意外的标识符”和“语法错误:缺少;声明之前”)。 It seemed like that error was usually for writing multiline strings in Javascript, which I don't think I'm trying to do.看起来这个错误通常是因为在 Javascript 中编写多行字符串,我认为我不想这样做。 d.endContext will print multi-line strings, but it works fine when I just pass ".", so I don't think that's the issue. d.endContext 将打印多行字符串,但是当我只传递“.”时它工作正常,所以我认为这不是问题。

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.match 返回的内容转换为布尔值。 If it returns a match, it is converted to true .如果它返回匹配项,则将其转换为true If it returns null , it is converted to false.如果它返回null ,则将其转换为 false。

Additionally, this app is quite good to learn Regex!此外,这个应用程序非常适合学习正则表达式! http://regexr.com/ http://regexr.com/

Have a nice day!祝你今天过得愉快! :D :D

Use the some and startsWith methods.使用somestartsWith方法。

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some 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. some() 方法测试数组中的某个元素是否通过提供的函数实现的测试。 Or you can also use regex或者你也可以使用正则表达式

/[.,:!?]/.test(string.charAt(0))

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 !因为我用了punky这个词! :D Oh and I treat the string as an array. :D 哦,我将字符串视为数组。 Which is nice!哪个好!

Has anyone else unit tested their code?有没有其他人对他们的代码进行过单元测试? :D :D

Using Array.prototype.indexOf is probably the simplest:使用Array.prototype.indexOf可能是最简单的:

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.它与 IE9 以及几乎所有 Chrome 和 Firefox(低至 1.5)版本兼容,但如果您使用的是 jQuery,则可以使用inArray进一步向后兼容。


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 :或者……只是为了好玩,你可以走到另一端,走在前沿,用新的 ES7 Array.prototype.includes打破所有非 beta 浏览器:

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) Chrome 47(尚未发布)
  • Firefox 43 (not yet released) Firefox 43(尚未发布)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM