How to remove a character from an array element?

I have an array like this:

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

and I would like to either remove the commas, \" , or replace them with " so that the array looks like this:

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

or that:

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

The reason is because I'm trying to pass this array from Ruby to JavaScript, but I keep getting the error message "Unterminated string constant" and I just can't figure out how to do this!

This is what I use to pass information to JavaScript:

 cut_list="from_ruby_cut(\""+c[1]+"\")" 
+6
source share
2 answers

To replace each element in the array with a modified version, for example, to replace an unnecessary character, you can use the map! function map! . 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 can solve your problem by using c[1].inspect instead of c[1] when creating a JavaScript string. If you use validation, it prints the quoted string and backslash to avoid quoting inside the string.

+10
source

To change the arrays the way you want, use map and gsub.

 a = ["ee", "3/4\"", "22\"", "22\""] a.map{|e| e.gsub(/"/,'')} => ["ee", "3/4", "22", "22"] 

or

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

However, I am not sure if this is the best way to achieve the ultimate goal.

0
source

Source: https://habr.com/ru/post/910375/


All Articles