Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a character from array element?

I have an array like this:

["ee", "3/4\"", "22\"", "22\""]

and I'd like to either remove the commas, \" or replace that with &#34 so that the array looks like this:

["ee", "3/4", "22", "22"]

or this:

["ee", "3/4&#34", "22&#34", "22&#34"]

The reason is that I'm trying to pass that array from Ruby to JavaScript, but I keep getting an "Unterminated string constant error" and I just can't figure out a way around it!

This is what I'm using to pass the info to JavaScript:

cut_list="from_ruby_cut(\""+c[1]+"\")"
like image 270
JoMojo Avatar asked Mar 09 '12 21:03

JoMojo


People also ask

How do I remove the first character from an array?

The shift() method removes the first item of an array.


1 Answers

To replace each element in an array with a modified version, such as replacing the unwanted character, you can use the map! function. Inside the block, use gsub to replace the unwanted " character.

array = ["ee", "3/4\"", "22\"", "22\""]

array.map!{ |element| element.gsub(/"/, '') }
array
#=> ["ee", "3/4", "22", "22"]

array.map!{ |element| element.gsub(/"/, '&#34') }
array
#=> ["ee", "3/4&#34", "22&#34", "22&#34"]

However, you may also be able to solve your problem by using c[1].inspect instead of c[1] when building your JavaScript string. If you use inspect, it'll print the string with the enclosing quotes included, and the backslash to escape the quote inside the string.

like image 52
Emily Avatar answered Nov 23 '22 07:11

Emily