I have an array like this:
["ee", "3/4\"", "22\"", "22\""]
and I'd like to either remove the commas, \"
or replace that with "
so that the array looks like this:
["ee", "3/4", "22", "22"]
or this:
["ee", "3/4"", "22"", "22""]
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]+"\")"
The shift() method removes the first item of an array.
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(/"/, '"') }
array
#=> ["ee", "3/4"", "22"", "22""]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With