所以问题是要求我从我的单词中删除标点符号,我知道如何交叉引用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;
}
答案 0 :(得分:3)
word.replace(/[;\!\.\?\,-]/g, '');
您可能会发现this非常有趣:D
答案 1 :(得分:1)
以下是基于您的代码的解决方案:
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('');
}
实现这一目标的另一种方法是:
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;
}
或者,如另一个答案所示:
function removePunctuation(word){
return word.replace(/[;\!\.\?\,-]/g, '');
}
答案 2 :(得分:0)
如果在数组中找不到值,则需要推送,所以:
punctuation.indexOf(chars[i]) == -1
但正则表达式似乎更简单。
为清楚起见,你需要遍历字符,只有在它们没有出现在标点符号数组中时才推送它们:
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(''))