1

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?

3 Answers 3

4

Step one

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.

Step two

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!');
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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 ./<>?;:"'`!@#$%^&*()[]{}_+=-|\\]<","<")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.