如何使用javascript替换字符串中最后匹配的字符 [英] How to replace last matched character in string using javascript
问题描述
我想将键盘上的最后一个输入字符替换为''
i want to replace last input character from keyboard to ''
我的字符串输入是
示例字符串
"<p><strong>abscd sample text</strong></p>"
"<p>abscd sample text!</p>"
我的最后一个角色是动态的,可以是介于两者之间的任何东西a 到 z、A 到 Z、0 到 9、任何特殊字符([~/< > & ( . ] ).所以我只需要替换那个字符
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
例如在示例 1 中我需要替换t",而在示例 2 中需要替换!"
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+'$/';
有什么办法吗?
推荐答案
第一步
替换字符串中的a字符,使用javaScript的replace()
函数.这里是 MDN 规范:
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.
您要替换的是第二个括号内的那个.因此,您使用与 $1
匹配的第一个括号中的相同字符串并替换其后的任何内容.
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!');
这篇关于如何使用javascript替换字符串中最后匹配的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!