[英]JavaScript: How can I remove any words containing (or directly preceding) capital letters, numbers, or commas, from a string?
我正在尝试编写代码,以便从字符串(文本)中删除“坏”字。
如果此词后带有逗号或任何特殊符号,则为“坏”。 如果该单词仅包含a to z
(小写字母),则不是“坏”字。
所以,我想要达到的结果是:
<script>
String.prototype.azwords = function() {
return this.replace(/[^a-z]+/g, "0");
}
var res = "good Remove remove1 remove, ### rem0ve? RemoVE gooood remove.".azwords();//should be "good gooood"
//Remove has a capital letter
//remove1 has 1
//remove, has comma
//### has three #
//rem0ve? has 0 and ?
//RemoVE has R and V and E
//remove. has .
alert(res);//should alert "good gooood"
</script>
好的,首先,您可能想在正则表达式中使用边界转义\\b
一词。 另外,如果您匹配错误的单词,这会有些棘手,因为错误的单词可能包含小写字符,因此您当前的正则表达式将排除任何包含小写字母的字符。
我很想挑出好词并将它们放在新的字符串中。 这是一个更容易的正则表达式。
/\b[a-z]+\b/g
注意:我不太确定它是否适用于字符串中的第一个和最后一个单词,因此您可能还需要考虑到这一点。 http://www.regextester.com/非常有用。
编辑:由于您希望在单词“坏”后加标点,这实际上可以完成我的建议
(^|\s)[a-z]+(\s|$)
尝试这个:
return this.replace(/(^|\s+)[a-z]*[^a-z\s]\S*(?!\S)/g, "");
它尝试匹配一个单词(由空格/字符串末尾包围),并且包含任何(非空格)字符,但至少一个不是az
字符。 但是,这非常复杂且无法维护。 也许您应该尝试一种更实用的方法:
return this.split(/\s+/).filter(function(word) {
return word && !/[^a-z]/.test(word);
}).join(" ");
试试这个:
var res = "good Remove remove1 remove, ### rem0ve? RemoVE gooood remove.";
var new_one = res.replace(/\s*\w*[#A-Z0-9,.?\\xA1-\\xFF]\w*/g,'');
//Output `good gooood`
说明 :
\s* # zero-or-more spaces
\w* # zero-or-more alphanumeric characters
[#A-Z0-9,.?\\xA1-\\xFF] # matches any list of characters
\w* # zero-or-more alphanumeric characters
/g - global (run over all string)
首先,如果可以避免的话,我不建议更改String(或任何本机对象)的原型,因为您可能会与其他可能以不同方式定义相同属性的代码发生冲突。 最好将这样的自定义方法放在命名空间对象上,尽管我敢肯定有些人会不同意。
第二,是否需要完全使用RegEx? (真正的问题;不要试图开玩笑。)
这是在这里和那里使用RegEx的普通JS的函数示例。 易于注释,调试和重用。
这是代码:
var azwords = function(str) {
var arr = str.split(/\s+/),
len = arr.length,
i = 0,
res = "";
for (i; i < len; i += 1) {
if (!(arr[i].match(/[^a-z]/))) {
res += (!res) ? arr[i] : " " + arr[i];
}
}
return res;
}
var res = "good Remove remove1 remove, ### rem0ve? RemoVE gooood remove."; //should be "good gooood"
//Remove has a capital letter
//remove1 has 1
//remove, has comma
//### has three #
//rem0ve? has 0 and ?
//RemoVE has R and V and E
//remove. has .
alert(azwords(res));//should alert "good gooood";
这将找到您想要的所有单词/ ^ [az] + \\ s | \\ s [az] + $ | \\ s [az] + \\ s / g,因此您可以使用match。
this.match(/^[az]+\\s|\\s[az]+$|\\s[az]+\\s/g).join(" ");
应该返回有效单词的列表。
请注意,作为JSFiddle花费了一些时间,因此拆分和迭代列表可能更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.