関数を*
使用して、特定の文字列のすべての文字を置き換えるにはどうすればよいreplaceAll()
ですか?
var words = ['marvel','computer','regex','throne'];
var rand = words[Math.floor(Math.random() * words.length)];
//should replace all characters in the string with *
$('#value').text(rand).replaceAll(rand,'*');
.container{
border: 1px solid black;
padding: 5px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<input type='text' />
<span id='value'></span>
<hr />
<button type='button' id='submit'>Submit</button>
</div>
正規表現のルートをたどらないほうがいいのですが、そうしなければならないのではないかと思います。
文字で文字列を隠す楽しみのための簡単な絞首刑執行人プログラムを書いています*
。次に、ユーザーは文字を入力し、正しい場合は文字列内の文字が元の文字にリセットされます。
正規表現は、このようなものに最適ですが、あまり馴染みがありません。
正規表現を使用したくない場合は、split()
文字列を配列に変換してからmap()
、条件に基づいて各要素を変更するために使用できます。
let replaceAll = (str, chars = []) => {
return str.split('')
.map(c => c.trim() && !chars.includes(c) ? '*' : c)
.join('');
}
console.log(replaceAll('lorem ipsum', ['l', 'm']))
console.log(replaceAll('123 lorem ips', ['2', 'i'] ))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加