目前,這是我的代碼。
function clean_string(raw_string) {
A =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890".split(
""
);
var cleaned_string = raw_string.toLowerCase();
for (i = 0; i < cleaned_string.length; i ) {
if (!A.includes(cleaned_string[i])) {
cleaned_string = setCharAt(cleaned_string, i, " ");
}
}
cleaned_string = cleaned_string.replace(/\s\s /g, " ");
return cleaned_string;
}
function setCharAt(str, index, chr) {
if (index > str.length - 1) return str;
return str.substring(0, index) chr str.substring(index 1);
}
我不知道正則運算式,使用正則運算式可能會更容易。這是我想要做的:
輸入: Hello, David World 123!
輸出: hello david world 123
.
輸入: hELlo., <>;dAVId world .;- 123
輸出: hello david world 123
.
輸入: He.llo David, w!orld 123#
輸出: he llo david w orld 123
.
基本上我想做的是用空格替換除 a-z0-9 之外的任何內容,然后洗掉雙空格。換句話說,我只想要 a-z0-9 在我的結果中。我怎樣才能做到這一點?
PS 該代碼有效,但我認為它看起來很糟糕而且效率很低。
編輯:抱歉,我的意思是我只想要輸出中的小寫字母。我很笨
uj5u.com熱心網友回復:
一個簡單的解決方案是將所有字符轉換為小寫,用空格字符替換不是 az、0-9 或空格的任何字符,然后用一個空格字符替換多個空格字符。
function sanitize(input) {
return input
.toLowerCase()
.replace(/([^a-z\d\s] )/g, ' ')
.replace(/(\s )/g, ' ');
}
console.log(sanitize('Hello, David World 123!'));
console.log(sanitize('hELlo., <>;dAVId world .;- 123'));
console.log(sanitize('He.llo David, w!orld 123#'));
uj5u.com熱心網友回復:
這是使用正則運算式回呼的一種方法:
var inputs = ["Hello, David World 123!", "hELlo., <>;dAVId world .;- 123", "He.llo David, w!orld 123#"];
for (var i=0; i < inputs.length; i) {
var input = inputs[i];
input = input.replace(/\w /g, x => x.toLowerCase())
.replace(/[^\w_] /g, " ");
console.log(input);
}
這里的策略是做兩個正則運算式替換。第一個找到輸入中的所有單詞并將它們轉換為小寫。第二個然后去除所有非單詞字符和空格,包括下劃線,并替換為單個空格。
uj5u.com熱心網友回復:
一個簡單的正則運算式來替換非字母數字字符,然后另一個在一行中洗掉多個空格應該可以解決問題。
const clean = (input) => {
const alphanumeric = input.replace(/[^a-zA-Z0-9]/g, ' ')
const spaceless = alphanumeric.replace(/\s{2,}/g, ' ')
console.log(spaceless.toLowerCase())
return spaceless.toLowerCase()
}
clean("Hello, David World 123!")
clean("hELlo., <>;dAVId world .;- 123")
clean("He.llo David, w!orld 123# ")
當然,函式可以縮短為
const clean = (input) => {
return input.replace(/[^a-zA-Z0-9]/g, ' ').
replace(/\s{2,}/g, ' ').
toLowerCase()
}
正則運算式說明:
[^a-zA-Z0-9]: 匹配任何不匹配 a-zA-Z0-9 (任何非字母數字)
\s{2,}: 匹配連續出現兩次或多次的空格
uj5u.com熱心網友回復:
您可以使用單個替換呼叫,或者只將大寫字符小寫,或者用一個空格替換 1 個或多個非單詞字符。
要區分替換和小寫,您可以在正則運算式中使用捕獲組并在回呼函式中檢查該組。
如果它匹配第 1 組,則有 1 個或多個大寫字符 AZ。
[
"Hello, David World 123!",
"hELlo., <>;dAVId world .;- 123",
"He.llo David, w!orld 123#"
].forEach(s =>
console.log(
s.replace(/([A-Z] )|[^\w_] /g, (_, g1) => g1 ? g1.toLowerCase() : ' ')
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404651.html
標籤:
