Reputation: 942
i want to replace last input character from keyboard to ''
My String Input are
sample string
"<p><strong>abscd sample text</strong></p>"
"<p>abscd sample text!</p>"
My last character is dynamic that can be any thing between a to z, A to Z, 0 to 9, any special characters([~ / < > & ( . ] ). So i need to replace just that character
for example in Sample 1 i need to replace "t" and in sample 2 in need to replace "!"
I tried below code. but it id not worked for me
var replace = '/'+somechar+'$/';
Any way to do it?
Upvotes: 1
Views: 10187
Reputation: 152956
Do you really need to use regular expressions? How about str = str.slice(0, -1);
? This will remove the last character.
If you need to replace a specific character, do it like this:
var replace = new RegExp(somechar + '$');
str = str.replace(replace, '');
You cannot use slashes in a string to construct a RegEx. This is different from PHP, for example.
Upvotes: 1
Reputation: 9288
to replace the a character in a string, use replace()
function of javaScript. Here is the MDN specification:
Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
you need to location the character to be replaced through regular expression. You want to replace the last character of a string and this could be expressed as /(.+)(.)$/. .
stands for any character, +
means more than one character. Here (.+)
matches all the character before the last one. (.)
matches the last character.
What you want to replace is the one inside the second brackets. Thus you use the same string matched in the first bracket with $1
and replace whatever after it.
Here is the code to realize your intention:
text = 'abscd sample text';
text.replace(/(.+)(.)$/, '$1!');
Upvotes: 4
Reputation: 4919
I dont really understand which character you want to replace to what, but i think, you should use replace() function in JS: http://w3schools.com/jsref/jsref_replace.asp
string.replace(regexp/substr,newstring)
This means all keyboard character:
[\t\n ./<>?;:"'`!@#$%^&*()[]{}_+=-|\\]
And this way you can replace all keyboard character before <
mark to ""
string.replace("[a-zA-Z0-9\t\n ./<>?;:"'`!@#$%^&*()[]{}_+=-|\\]<","<")
Upvotes: 0