[英]How to push only the elements not found in my array
So the question is asking me to remove punctuation from my word and i know how to cross-reference the tho arrays to check if an element exists in my array to be checked but how do i only push the values that are not in my punctuation array? 所以问题是要我从单词中删除标点符号,并且我知道如何交叉引用tho数组以检查要检查的数组中是否存在某个元素,但是我如何仅推送标点数组中不存在的值?
function removePunctuation(word){
var punctuation = [";", "!", ".", "?", ",", "-"];
var chars = word.split("");
var puncRemoved = [];
for(var i = 0; i < chars.length;i++){
for(var j = 0; j < punctuation.length;j++) {
if(punctuation[j].indexOf(chars[i]) !== 0) {
puncRemoved.push(i)
}
}
}
return puncRemoved;
}
word.replace(/[;\!\.\?\,-]/g, '');
您可能会发现这很有趣:D
Here's a solution which is based on your code: 这是一个基于您的代码的解决方案:
function removePunctuation(word){
var punctuation = [";", "!", ".", "?", ",", "-"];
var chars = word.split("");
var puncRemoved = [];
for (var i = 0; i < chars.length; i++) {
// Push only chars which are not in punctuation array
if (punctuation.indexOf(chars[i]) === -1) {
puncRemoved.push(chars[i]);
}
}
// Return string instead of array
return puncRemoved.join('');
}
Another way to implement this would be: 实现此目的的另一种方法是:
function removePunctuation(word){
var punctuation = [";", "!", ".", "?", ",", "-"];
// Iterate and remove punctuations from the given string using split().join() method
punctuation.forEach(function (p) {
word = word.split(p).join('');
});
return word;
}
Or, as suggested in another answer: 或者,如另一个答案所示:
function removePunctuation(word){
return word.replace(/[;\!\.\?\,-]/g, '');
}
You need to push the value when it's not found in the array, so: 如果在数组中找不到该值,则需要推送该值,因此:
punctuation.indexOf(chars[i]) == -1
but a regular expression seems so much simpler. 但是正则表达式看起来要简单得多。
To make it clear, you need to iterate over the characters and only push them if they don't appear in the punctuation array: 为了清楚起见,您需要遍历字符,并且仅当它们未出现在标点符号数组中时才推送它们:
function removePunctuation(word){ var punctuation = [";", "!", ".", "?", ",", "-"]; var chars = word.split(""); var puncRemoved = []; for(var i = 0; i < chars.length;i++){ if(punctuation.indexOf(chars[i]) == -1) { puncRemoved.push(chars[i]) } } return puncRemoved; } var s = 'Hi! there. Are? you; ha-ppy?'; console.log(removePunctuation(s).join(''))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.