如何检查字符串是否包含符号列表?

时间:2016-10-31 20:07:28

标签: javascript jquery

我有一份唱歌清单:

var sings = [",",".",":","!","?"]

如何检查某个单词是否包含其中一个符号并将其返回?

例如:

"But,"

return ","

"Finished."

return "."

"Questions?"

return "?"

4 个答案:

答案 0 :(得分:3)

你可以用正则表达式解决这个问题:

function match(input) {
  var regex = /([,\.\:!\?])/;
  var matches = input.match(regex);
  return matches ? matches[0] : false;
}

console.log(match("foo?"));   // "?"
console.log(match("bar."));   // "."
console.log(match("foobar")); // false

答案 1 :(得分:2)

这是示例函数

var checkSigns = function(str) {
    var signs = [",",".",":","!","?"];

    for (var i = 0; i < signs.length; i++) {
        if (str.indexOf[signs[i]] !== -1) {
            return signs[i];
        }
    }
};

答案 2 :(得分:1)

您可以使用filter()indexOf()并返回在字符串中找到的符号数组。

&#13;
&#13;
var signs = [",",".",":","!","?"];
function check(str, arr) {
  return arr.filter(function(e) {
    return str.indexOf(e) != -1
  })
}

console.log(check("But,", signs))
console.log(check("Finished.", signs))
&#13;
&#13;
&#13;

答案 3 :(得分:1)

如果包含,请尝试此原型str.hasSign();返回sign或如果不包含false

String.prototype.hasSigns = function() {
  var signs = [",", ".", ":", "!", "?"];
  for (var i = 0; i < signs.length; i++) {
    if (this.indexOf(signs[i]) > -1) return signs[i];
  }
  return false;
}

console.log("football, basketball".hasSigns());

console.log("1-3".hasSigns());

console.log("Good!".hasSigns());