Akhil Akhil - 5 months ago 17
Javascript Question

Passing dynamic string variables with special character to JQuery Function

I generated custom checkbox for select or unselect my data. I have 2 custom functions for selecting and unselecting data. In the select method i need to pass 2 variables and it is field value.

My code:

<span custom-checkbox="true"
is-checked="false"
name="id"
data-val="{this.id}"
on-select="DataSelect('{this.id+'\',\'' +this.name}')"
on-unselect="DataUnselect('{this.id}')" id="{this.id}">
</span>

function DataSelect(id, value){
console.log(id);
console.log(value);
//my code
}

function DataUnselect(id, value){
//my code
}


Issue:

name field contains special characters like quotes (''). the following are the sample data;

id = "1";
name= "hey'len";


Here i got the issue due to the quote('). So data manipulated as ;

DataSelect('1', 'hey'len')


So i got as "Uncaught SyntaxError: missing ) after argument list".

Please help me correct this

Answer

You can escape quotes from string using .replace()

id = "1";
name= "hey'len";
name.replace('\'', '\\\'');