【问题标题】:find uppercase letters and conver them into lower case vice versa using js regex使用js正则表达式查找大写字母并将它们转换为小写反之亦然
【发布时间】:2019-10-25 14:28:38
【问题描述】:
document.getElementById('generate').addEventListener('click', createPassword)

function createPassword(){
    var len= document.getElementById('length').value;
    var password=''

    for(let i=0; i<len; i++){
        var random= Math.floor(Math.random()*94)+33
        password+= String.fromCharCode(random)
    }

    document.getElementById('result').innerText=password;

    var uppercase= document.getElementById('uppercase')
    var upperCheck= uppercase.checked


    if(upperCheck!=true){

        var result=password.replace(/[A-Z]/g,/\U$1$2/);

        console.log(result)
    }



}

我正在尝试遍历随机创建的字符串,并使用正则表达式将所有大写字母转换为小写字母,反之亦然。

【问题讨论】:

  • String.prototype.toLowerCase 有什么问题?首先没有随机包含大写字母有什么问题?它必须是正则表达式吗?
  • 随机字符串包含特殊字符,所以该选项不起作用。

标签: javascript regex


【解决方案1】:

您可以使用函数作为replace 方法的第二个参数来使用带有正则表达式的toLower/toUpperCase 函数:

document.getElementById('generate').addEventListener('click', createPassword)

function createPassword(){
    var len= document.getElementById('length').value;
    var password=''

    for(let i=0; i<len; i++){
        var random= Math.floor(Math.random()*94)+33
        password+= String.fromCharCode(random)
    }

    document.getElementById('result').innerText="Generated: "+ password;

    var uppercase= document.getElementById('uppercase')

    var modified;
    console.clear(); // just to clear console if retried.
    if (uppercase.checked){
        modified = password.replace(/[a-z]/g,  function(match) {return match.toUpperCase(); });
    } else {
        modified = password.replace(/[A-Z]/g,  function(match) {return match.toLowerCase(); });
    }
    console.log("Modified:", modified)
}
<input type="text" id="length" value ="10"/>

<input type="button" value="generate" id="generate"/>
<input type="checkbox" id="uppercase"/>
<p id="result"></p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2016-02-24
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2014-12-21
    相关资源
    最近更新 更多