[英]Removing all special characters except "some" apostrophes
我正在嘗試創建一個函數,當它們自然是單詞的一部分時,刪除除撇號之外的所有特殊字符(包括句點)。 我所做的正則表達式模式應該刪除任何不符合word
模式的內容,后跟撇號'
和/或另一個word
:
function removeSpecialCharacters(str) { return str.toLowerCase().replace(/[^az?'?az ]/g, ``) } console.log(removeSpecialCharacters(`I'm a string.`)) console.log(removeSpecialCharacters(`I'm a string with random stuff.*/_- '`)) console.log(removeSpecialCharacters(`'''`))
正如您從代碼片段中看到的那樣,除了刪除流氓撇號之外,它運行良好。
如果我在模式中添加[\\s'\\s]
或[']
,它會完全破壞它。 為什么要這樣做,我在這里錯過了什么?
用'\\B
替換模式,這將匹配並刪除后面沒有單詞字符的撇號,例如ab'
或ab'@
,同時保留像ab'c
這樣的ab'c
:
function removeSpecialCharacters(str) { return str.toLowerCase().replace(/'\\B|[^a-z'? ]/g, ``) } console.log(removeSpecialCharacters(`I'm a string.`)) console.log(removeSpecialCharacters(`I'm a string with random stuff.*/_- '`)) console.log(removeSpecialCharacters(`'''`))
(您也可以從字符集中刪除重復的字符)
這是一個非常簡單的解決方案。 要從字符串中刪除某些特征,您可以通過 while 循環運行一堆 if 語句。 這使您可以准確選擇要刪除的符號。
while (increment < string.length)
{
if (string[increment] == "!")
}
delete "!";
}
increment += 1;
}
這是一個簡單的概述(不是實際代碼),讓您了解自己在做什么。
不知道你的出了什么問題,因為我看不到你的嘗試。 但是,我讓這個工作。
function removeSpecialCharacters(str) { str = str.toLowerCase(); // reduce duplicate apostrophes to single str = str.replace(/'+/g,`'`); // get rid of wacky chars str = str.replace(/[^a-z'\\s]/g,''); // replace dangling apostrophes str = str.replace(/(^|\\s)'(\\s|$)/g, ``); return str; } console.log(removeSpecialCharacters(`I'm a string.`)) console.log(removeSpecialCharacters(`I'm a string with random stuff.*/_- '`)) console.log(removeSpecialCharacters(`'''`)) console.log(removeSpecialCharacters(`regex 'til i die`))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.