Convert string to readable variable...


I"m looking to convert a string so my jquery script works...

The line is... var myUserID = $('#id_'+myID).val();

but it's not working because my variable "myID" uses other characters besides numbers.


How can I convert the string so it can be used in this line?

Who is Participating?
Roman GhermanConnect With a Mentor Senior Software EngineerCommented:

I don't think there should be a problem with the "-" character because it is allowed.

Here is a list of jQuery special characters:

What you need to do is to find a function to escape the string.
Gurvinder Pal SinghCommented:
make it

 var myUserID = $('#id_"'+myID +'" ').val();
Roman GhermanSenior Software EngineerCommented:
here is a function to escape the selector value that I have found. please test if it works for you:

function escapeStr( str) {
 if( str)
     return str.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g,'\\$1')
     return str;

Open in new window

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

leakim971Connect With a Mentor PluritechnicianCommented:
If you've really something special : $("[id='id_" + myID + "']").val();
Roman GhermanSenior Software EngineerCommented:
Hi leakim971,

I think in your case will not handle if myID contains '
My opinion is that the best thing that you can do is to escape the string
You right roma1123, I hope there's no << ' >> in the id...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.