如果我有一个字符串,其中有任何类型的非字母数字字符:

"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"

我如何在JavaScript中得到一个没有标点符号的版本:

"This is an example of a string with punctuation"

当前回答

它很简单,只是替换字符而不是单词:

.replace(/[^\w]/g, ' ')

其他回答

str = str.replace(/[^\w\s\']|_/g, "")
         .replace(/\s+/g, " ");

删除除字母数字字符和空白之外的所有内容,然后将多个相邻空白折叠为单个空格。

详细解释:

\w是任意数字、字母或下划线。 \s是任何空白。 [^\w\s\']是指任何不是数字、字母、空格、下划线或单引号的字符。 [^\w\s\']|_与#3相同,只是加了下划线。

/[^A-Za-z0-9\s]/g应该匹配所有的标点符号,但要保留空格。 因此,如果需要的话,可以使用.replace(/\s{2,}/g, " ")替换额外的空格。您可以在http://rubular.com/中测试正则表达式

.replace(/[^A-Za-z0-9\s]/g,"").replace(/\s{2,}/g, " ")

更新:只有当输入是ANSI英语时才会工作。

如果您正在使用lodash

_.words('This, is : my - test,line:').join(' ')

这个例子

_.words('"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"').join(' ')

如果你想从任何字符串中删除标点符号,你应该使用P Unicode类。

但是,由于JavaScript RegEx不接受类,您可以尝试这个RegEx,它应该匹配所有的标点符号。它匹配以下类别:Pc Pd Pe Pf Pi Po Ps Sc Sk Sm So一般标点符号补充标点符号CJKSymbolsAndPunctuation cuneiformnumber和punctuation。

我使用这个在线工具创建了它,它专门为JavaScript生成正则表达式。 这是实现你目标的代码:

var punctuationRegEx = /[!-/:-@[-`{-~¡-©«-¬®-±´¶-¸»¿×÷˂-˅˒-˟˥-˫˭˯-˿͵;΄-΅·϶҂՚-՟։-֊־׀׃׆׳-״؆-؏؛؞-؟٪-٭۔۩۽-۾܀-܍߶-߹।-॥॰৲-৳৺૱୰௳-௺౿ೱ-ೲ൹෴฿๏๚-๛༁-༗༚-༟༴༶༸༺-༽྅྾-࿅࿇-࿌࿎-࿔၊-၏႞-႟჻፠-፨᎐-᎙᙭-᙮᚛-᚜᛫-᛭᜵-᜶។-៖៘-៛᠀-᠊᥀᥄-᥅᧞-᧿᨞-᨟᭚-᭪᭴-᭼᰻-᰿᱾-᱿᾽᾿-῁῍-῏῝-῟῭-`´-῾\u2000-\u206e⁺-⁾₊-₎₠-₵℀-℁℃-℆℈-℉℔№-℘℞-℣℥℧℩℮℺-℻⅀-⅄⅊-⅍⅏←-⏧␀-␦⑀-⑊⒜-ⓩ─-⚝⚠-⚼⛀-⛃✁-✄✆-✉✌-✧✩-❋❍❏-❒❖❘-❞❡-❵➔➘-➯➱-➾⟀-⟊⟌⟐-⭌⭐-⭔⳥-⳪⳹-⳼⳾-⳿⸀-\u2e7e⺀-⺙⺛-⻳⼀-⿕⿰-⿻\u3000-〿゛-゜゠・㆐-㆑㆖-㆟㇀-㇣㈀-㈞㈪-㉃㉐㉠-㉿㊊-㊰㋀-㋾㌀-㏿䷀-䷿꒐-꓆꘍-꘏꙳꙾꜀-꜖꜠-꜡꞉-꞊꠨-꠫꡴-꡷꣎-꣏꤮-꤯꥟꩜-꩟﬩﴾-﴿﷼-﷽︐-︙︰-﹒﹔-﹦﹨-﹫!-/:-@[-`{-・¢-₩│-○-�]|\ud800[\udd00-\udd02\udd37-\udd3f\udd79-\udd89\udd90-\udd9b\uddd0-\uddfc\udf9f\udfd0]|\ud802[\udd1f\udd3f\ude50-\ude58]|\ud809[\udc00-\udc7e]|\ud834[\udc00-\udcf5\udd00-\udd26\udd29-\udd64\udd6a-\udd6c\udd83-\udd84\udd8c-\udda9\uddae-\udddd\ude00-\ude41\ude45\udf00-\udf56]|\ud835[\udec1\udedb\udefb\udf15\udf35\udf4f\udf6f\udf89\udfa9\udfc3]|\ud83c[\udc00-\udc2b\udc30-\udc93]/g; var string = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"; var newString = string.replace(punctuationRegEx, '').replace(/(\s){2,}/g, '$1'); console.log(newString)

下面是US-ASCII的标准标点符号:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

对于Unicode标点符号(如大引号、em-dash等),可以很容易地匹配特定的块范围。一般标点符号块是\u2000-\u206F,补充标点符号块是\u2E00-\u2E7F。

放在一起,并正确转义,您将得到以下RegExp:

/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/

这应该可以匹配您遇到的任何标点符号。那么,来回答最初的问题:

var punctRE = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/g;
var spaceRE = /\s+/g;
var str = "This, -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
str.replace(punctRE, '').replace(spaceRE, ' ');

>> "This is an example of a string with punctuation"

US-ASCII来源:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#posix

Unicode来源:http://kourge.net/projects/regexp-unicode-block