Clicking on a title should replace its last letter with *
. In the example below the results should be gol*
, silve*
, su*
. Any help?
$('.title').on('click', function() { let a = $(this).text(); //let b = a.replace_last_letter_with "*" $(this).text(b) });
.title { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>gold</div> <div class='title'>silver</div> <div class='title'>sun</div>
You can do this work using String.slice()
$('.title').on('click', function(){ $(this).text(function(i, t){ return t.slice(0, -1)+"*"; }); });
.title{cursor:pointer}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>gold</div> <div class='title'>silver</div> <div class='title'>sun</div>
You can use a simple Regex to select the last letter of the text and set it to *
. Also note that you can provide a function to text()
which accepts the current value as an argument and returns the new value to set. Try this:
$('.title').on('click', function() { $(this).text(function(i, t) { return t.trim().replace(/.$/, '*'); }); });
.title { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>gold</div> <div class='title'>silver</div> <div class='title'>sun</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.