如何使用 javascript 替换字符串右端的第 x 个字符?
我必须在图像 src
属性中找到 "b"
并将其替换为 "g"
。
初始 src 类似于 "someName-b.png"
,使用 JavaScript,我必须将 "b"
替换为 "g".但问题是
"someName"
的长度可能不同。所以基本上我想做的是找到 src 属性字符串末尾的第 5 个字符,然后将第 5 个字符替换为 "g"
。
JavaScript 中是否有一个函数可以让我从字符串末尾找到第 x 个字符?
I have to find and replace the "b"
with "g"
in the image src
attribute.
The initial src would be something like "someName-b.png"
, and with JavaScript, I have to replace the "b"
with "g"
. But the problem is the "someName"
can differ in length. So basically what I want to do is find the 5th character from the end of the src attribute string, and then replace the 5th char to "g"
.
Is there a function in JavaScript that allows me to find the x
th character from the end of a string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
.slice
。对于负值,该函数从右侧计数:You can use
.slice
. With negative values, this function counts from the right:查找字符串末尾的第 5 个字符:
string.charAt(string.length - 5)
。替换字符串末尾的第 5 个字符:
string.substring(0, string.length -5) + 'g' + string.substring(string.length - 4)
Find the 5th character from end of a String:
string.charAt(string.length - 5)
.Replace the 5th character from the end of a String:
string.substring(0, string.length -5) + 'g' + string.substring(string.length - 4)
可能不是正则表达式的工作,但是嘿,它有效:
Probably not a job for regular expressions, but hey, it works: