所以问题是要求我从单词中删除标点符号,我知道如何交叉引用 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
下面是一个基于您的代码的解决方案:
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, '');
}
当数组中找不到值时,您需要推送该值,因此:
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(''))