我想将下面的字符串转换为提供的输出。

Input:  "\\test\red\bob\fred\new"
Output: "testredbobfrednew"

我还没有找到任何解决方案,将处理特殊字符,如\r, \n, \b等。

基本上我只是想去掉所有不是字母数字的东西。以下是我尝试过的方法……

Attempt 1: "\\test\red\bob\fred\new".replace(/[_\W]+/g, "");
Output 1:  "testedobredew"

Attempt 2: "\\test\red\bob\fred\new".replace(/['`~!@#$%^&*()_|+-=?;:'",.<>\{\}\[\]\\\/]/gi, "");
Output 2:  "testedobred [newline] ew"

Attempt 3: "\\test\red\bob\fred\new".replace(/[^a-zA-Z0-9]/, "");
Output 3:  "testedobred [newline] ew"

Attempt 4: "\\test\red\bob\fred\new".replace(/[^a-z0-9\s]/gi, '');
Output 4:  "testedobred [newline] ew"

另一次尝试有多个步骤

function cleanID(id) {
    id = id.toUpperCase();
    id = id.replace( /\t/ , "T");
    id = id.replace( /\n/ , "N");
    id = id.replace( /\r/ , "R");
    id = id.replace( /\b/ , "B");
    id = id.replace( /\f/ , "F");
    return id.replace( /[^a-zA-Z0-9]/ , "");
}

结果

Attempt 1: cleanID("\\test\red\bob\fred\new");
Output 1: "BTESTREDOBFREDNEW"

任何帮助都将不胜感激。

工作方案:

Final Attempt 1: return JSON.stringify("\\test\red\bob\fred\new").replace( /\W/g , '');
Output 1: "testredbobfrednew"

当前回答

如果你有除英语以外的其他语言的情况,你需要添加相对块范围从unicode。下面是一个西里尔字母的例子:

.replace(/[^0-9A-Za-z_\u0400-\u04FF]/gi, '')

其他回答

如果你有除英语以外的其他语言的情况,你需要添加相对块范围从unicode。下面是一个西里尔字母的例子:

.replace(/[^0-9A-Za-z_\u0400-\u04FF]/gi, '')

这里有一个你可以用的例子,

function removeNonAlphaNumeric(str){
    return str.replace(/[\W_]/g,"");
}

removeNonAlphaNumeric("0_0 (: /-\ :) 0-0");

目前所有的答案都有怪癖,我能想到的最好的答案是:

string.replace(/[^A-Za-z0-9]/g, '');

下面的例子囊括了我能在键盘上找到的每个键:

var string = '123abcABC-_*(!@#$%^&*()_-={}[]:\"<>,.?/~`';
var stripped = string.replace(/[^A-Za-z0-9]/g, '');
console.log(stripped);

产出:“123abcABC”。

这将删除所有非字母数字字符,保留大写并保留单词之间的空格。

function alpha_numeric_filter (string) {

  const alpha_numeric = Array.from('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + ' ')

  const json_string = JSON.stringify(string)

  let filterd_string = ''

  for (let i = 0; i < json_string.length; i++) {

    let char = json_string[i]
    let index = alpha_numeric.indexOf(char)
    if (index > -1) {
      filterd_string += alpha_numeric[index]
    }

  }

  return filterd_string

}

const input = "\\test\red\bob\fred\new"
console.log(alpha_numeric_filter(input)) //=> testredbobfrednew

const complex_string = "/_&_This!&!! is!@#$% a%^&*() Sentence+=-[]{} 123:;\|\\]||~`/.,><"
console.log(alpha_numeric_filter(complex_string)) //=> This is a Sentence 123

要包含阿拉伯字母和英语字母,你可以使用:

// Output: نصعربي
"ن$%^&*(ص ع___ربي".replace(/[^0-9a-z\u0600-\u06FF]/gi, '');