[英]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
}
您可以簡單地使用包含和替換
a
和i
存在a
和i
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.