簡體   English   中英

驗證 JavaScript 中任何兩個特定字母的輸入,例如“a”和“i”,並將“a”替換為 @,將“i”替換為?

[英]Validate input of any two specific letters say 'a' and 'i' in JavaScript and replace 'a' with @ and 'i' with?

我是新手,在這里需要幫助。 我們需要來自用戶的輸入字符串。 輸入字符串必須同時包含字母'a''i' 如果它不包含兩者,那么我們拒絕輸入並提醒用戶。

如果輸入字符串同時包含'a''i'那么我們將a with @ and i with !替換a with @ and i with !替換a with @ and i with ! .然后我們打印輸出。

例如: aletis-->@lert!s

我試過

var check = /[aiAI]/;

但這需要輸入,即使只有 a 或 i 滿足。

如果您真的不熟悉正則表達式,我建議您分兩步進行,因為這樣會更清晰易讀。

"alertis".replace(/a/gi, "@").replace(/i/gi, "!");

/a/gi 表示查找“a”,/gi 表示“不區分大小寫”和全局。

if (/(?=.*a)(?=.*i).*/.test('aletis')) {
    const result = "aletis".replace(/a/gi, "@").replace(/i/gi, "!");
    // Rest of your code
} else {
    // SHOW ERROR
}

您可以簡單地使用包含和替換

  • 首先獲取輸入元素的值
  • 更改為小寫並檢查ai存在
  • 如果存在,則用各自的值替換ai

 function handleSubmit(e) { e.preventDefault() let element = document.getElementById('input').value let lowerCased = element.toLowerCase() if (lowerCased.includes('a') && lowerCased.includes('i')) { console.log(element.replace(/a/gi, '@').replace(/i/gi, '!')) } }
 <form onsubmit='handleSubmit(event)'> <input id='input'> <button type='submit'>Submit</button> </form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM