I have strings like Name:, Call:, Phone:....and so on in my table. I am learning jQuery and was able to access the text. My tutorial has used trim()
to remove any whitespaces. But I want o remove ":" from the end of each string (and yes, it always lies in the end after calling trim()
method). So how to achieve it.
Its my code:
<script type="text/javascript">
$(function ()
{
$(':input[type=text], textarea').each
(
function ()
{
var newText = 'Please enter your ' +
$(this).parent().prev().text().toLowerCase().trim();
$(this).attr('value', newText);
}).one('focus', function ()
{
this.value = '', this.className = ''
}).addClass('Watermark').css('width', '300px');
});
</script>
trim(":") did not help...
In Python you can use the replace() and translate() methods to specify which characters you want to remove from the string and return a new modified string result. It is important to remember that the original string will not be altered because strings are immutable.
In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed.
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb.
You can replace all :
characters:
var str = '::a:sd:';
str = str.replace(/:/g,''); // str = 'asd';
Or use a handy rtrim()
function:
String.prototype.rtrim = function(character) {
var re = new RegExp(character + '*$', 'g');
return this.replace(re, '');
};
var str = '::a:sd:';
str = str.rtrim(':'); // str = '::a:sd';
In this case just use the plain old JavaScript replace
or substr
methods.
You can also use a regular expression that looks for colon as the last character (the character preceding the regexp end-of-string anchor "$").
"hi:".replace(/:$/, "")
hi
"hi".replace(/:$/, "")
hi
"h:i".replace(/:$/, "")
h:i
This is a simplified, inline version of the rtrim
function in Blender's answer.
EDIT: Here is a test fiddle for Blender's corrected rtrim
function. Note that his RegExp will delete multiple occurrences of the specified character if the string ends with multiple instances of it consecutively (example bolded below).
http://jsfiddle.net/fGrPb/5/
input = '::a:sd:' output = '::a:sd'; input = 'hi:' output = 'hi'; input = 'hi:::' output = 'hi'; input = 'hi' output = 'hi'; input = 'h:i' output = 'h:i'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With