0

I need to replace all special characters within a string with their index. For example,

"I-need_to@change$all%special^characters^"

should become:

"I1need6to9change16all20special28characters39"

The index of all special character differs. I have checked many links replacing all with single character, occurances of a character. I found very similar link but it I do not want to adopt these replace its index number as I need to replace all of the special characters.

I have also tried to do something like this:

str.gsub!(/[^0-9A-Za-z]/, '')

Here str is my example string. As this replaces all the characters but with space, and I want the index instead of space. Either all of the special character or these seven

\/*[]:?

I need to replace this seven mainly but it would be OK if we replace all of them.

I need a simpler way.

Thanks in advance.

Community
  • 1
  • 1
Manishh
  • 1,444
  • 13
  • 23

1 Answers1

2

You can use the global variable $` and the block form of gsub:

irb> str = "I-need_to@change$all%special^characters^"
=> "I-need_to@change$all%special^characters^"
irb> str.gsub(/[^0-9A-Za-z]/) { $`.length }
=> "I1need6to9change16all20special28characters39"
Dogbert
  • 212,659
  • 41
  • 396
  • 397