Akhil
Akhil

Reputation: 2030

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

Upvotes: 1

Views: 2412

Answers (3)

VnDevil
VnDevil

Reputation: 1391

If your replace string have special charaters you have to replace it before create RegExp like this:

var html = `
<div>This is Html</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's m</div>
<p>asdasdasally unchanged. It was popularised in the 1960s with the release of Letraset sheets <span>
<img src="https://via.placeholder.com/200x100?w=100" />
the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it </span>
to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>
`;

var oldImage = 'https://via.placeholder.com/200x100?w=100';
var newImage = 'https://via.placeholder.com/350x150?w=1000';

var fixOldImageToRegExp = oldImage.replace(/\//g, '\\/').replace(/\?/g, '\\?').replace(/\w/g, '\\w');
var re = new RegExp(fixOldImageToRegExp,'gi');
document.write(html.replace(re, newImage));

and this is running codepen

Upvotes: 0

Rakesh Kumar
Rakesh Kumar

Reputation: 4420

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

Use this it will replace all occurance of ('). It also work fine with "hey'len'new'something".

Try It

Upvotes: 1

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

You can escape quotes from string using .replace()

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

Upvotes: 2

Related Questions