arun nair
arun nair

Reputation: 3683

how do i replace the x'th character from the right end of a string using javascript?

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 xth character from the end of a string?

Upvotes: 1

Views: 256

Answers (3)

pimvdb
pimvdb

Reputation: 154828

You can use .slice. With negative values, this function counts from the right:

var a = "123456789"; // sample string

a.slice(0, -5)  // slice from begin to 5th character before end
 + "g"          // add a 'g'
 + a.slice(-4); // slice last 4 characters

// result: 1234g6789

Upvotes: 5

Vala
Vala

Reputation: 5674

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)

Upvotes: 3

Felix
Felix

Reputation: 89576

Probably not a job for regular expressions, but hey, it works:

> "someName-b.png".replace(/.(.{4})$/, "g$1")
-> "someName-g.png"

Upvotes: 1

Related Questions