替换字符串中最后出现的字符 [英] Replace last occurrence of character in string
本文介绍了替换字符串中最后出现的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在jQuery中有一种简单的方法可以替换给定字符串中最后一次出现的'_'(下划线)吗?
Is there an easy way in jQuery to replace the last occurrence of an '_' (underscore) in a given string?
推荐答案
你不需要jQuery,只需要一个正则表达式。
You don't need jQuery, just a regular expression.
这将删除最后一个下划线:
This will remove the last underscore:
var str = 'a_b_c';
str = str.replace(/_([^_]*)$/,'$1'); //a_bc
这将用变量 replacement <的内容替换它/ code>:
This will replace it with the contents of the variable replacement
:
var str = 'a_b_c', replacement = '!';
str = str.replace(/_([^_]*)$/,replacement+'$1'); //a_b!c
这篇关于替换字符串中最后出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文