String substitution?

R

Roberto Rivera

Hello,

Im working on a small rails app that uses a text editor component
(FCKEdit). In certain cases, the editor will add characters to my string
that I need to remove before I show the output.

For example, it will add '\' in front of any '"' or '\' in my document.

I was checking out String.replace and String.gsub, but they both seem to
replace any element that matches the input string.

"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"

In my particular case, I need it to match the whole string for
substitution.

I worked out this code in order to substitute '\"' for '"' and '\\' for
'\':

<%= text.split('\"').join('"').split("\\\\").join("\\") %>

Im sure there's gotta be some other way to make it work without breaking
it into arrays and rejoining.

Any help will be appreciated.
az
 
R

Robert Dober

Hello,

Im working on a small rails app that uses a text editor component
(FCKEdit). In certain cases, the editor will add characters to my string
that I need to remove before I show the output.

For example, it will add '\' in front of any '"' or '\' in my document.

I was checking out String.replace and String.gsub, but they both seem to
replace any element that matches the input string.

"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"

In my particular case, I need it to match the whole string for
substitution.

I worked out this code in order to substitute '\"' for '"' and '\\' for
'\':

<%= text.split('\"').join('"').split("\\\\").join("\\") %>
First of all there is nothing wrong with this(1), I like it a lot,
however as you have asked;)

text.gsub('\"','"').gsub("\\\\","\\")

might indeed be considered a little bit more concise.

Funny how this pattern just matches my previous post in the string
replacement thread.

HTH
Robert
(1) With the exception of a trailing \" or \\"
 
R

Roberto Rivera

Robert said:
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"

In my particular case, I need it to match the whole string for
substitution.

I worked out this code in order to substitute '\"' for '"' and '\\' for
'\':

<%= text.split('\"').join('"').split("\\\\").join("\\") %>
First of all there is nothing wrong with this(1), I like it a lot,
however as you have asked;)

text.gsub('\"','"').gsub("\\\\","\\")

might indeed be considered a little bit more concise.

Funny how this pattern just matches my previous post in the string
replacement thread.

HTH
Robert
(1) With the exception of a trailing \" or \\"

Indeed, I was trying to get a more concise alternative. Yours is
perfect.
Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top