I have this code:
$(".value").append($("#txtValue").val()).attr("class", "values");
Example: If the #txtValue
value is 'Apple, Banana,' how can I remove the comma (, ) to last last value using the code I have in the above or if it detected that the value has the last string of comma (,). I just want to have the get the value like this: 'Apple, Banana'
You could use slice :
var val = $("#txtValue").val(),
txt = val.slice(-1) === ',' ? val.slice(0, - 1) : val;
$(".value").append(txt).attr("class", "values");
或使用正则表达式:
var str = 'Apple, Banana,'.replace(/,$/, '');
var string = "Apple,Banana,"; var lastIndex = string.lastIndexOf(","); if((string.length - 1) == lastIndex){ console.log(string.substring(0,lastIndex)); }
Another solution but regexp is a good method i think.
<html>
<head></head>
<body>
<script>
//Make a .trim() before
var stuff = "Apple, Banana,";
var result = (stuff.substr(stuff.length-1, 1) == ",")? stuff.substr(0, stuff.length-1):stuff;
alert(result);
</script>
</body>
</html>
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.