Reputation:
I have a variable:
a = "test data";
a = "test data!";
How can I remove the '!' if it exists at the end of the string? If possible I am looking for a method that would be the most clean solution.
Upvotes: 0
Views: 273
Reputation: 63
if you didn't want to use a regular expression, you could use this logic. The syntax below is in javascript, because I'm on a NodeJS kick these days, but you could tailor to any language.
function removeTrailExclamation(str) {
return str.charAt(str.length-1) == '!' ? str.substring(0,str.length-1) : str;
}
If you're not comfortable with conditional operators
function removeTrailExclamation(str) {
if(str.charAt(str.length-1) == '!') {
return str.substring(0,str.length-1);
} else {
return str;
}
}
Hope that helps!
Upvotes: 1
Reputation: 3462
if you want to replace only at the end... using substring
if(a.charAt(a.length - 1)=='!')
a.substring(0, a.length - 1);
if every where..
a..replace(!, '');
Upvotes: 0
Reputation: 145408
The shortest way is to use regular expression with !$
, which means "match exclamation !
mark right before the end $
of the string":
'test data!'.replace(/!$/, '');
Upvotes: 5