Terje Nygård
Terje Nygård

Reputation: 1257

Jquery : .replace part of string returns "Unexpected token ILLEGAL"

I have googled, and browsed around for this really, really weird but known error for a while now, but i just cannot figure out what's wrong with this code, and why it gives me the error "Unexpected token ILLEGAL".

The line that fails is this one :

var temp = existingTags.replace(tagToRemove, '');​

CODE :

onDelete: function (item) {
    var existingTags = $('.lblTags').html();
     var tagToRemove = item.name + ',';
     var temp = existingTags.replace(tagToRemove, '');​
     $('.lblTags').text(temp);
}

DATA :

existingTags = "Oddity,Strange,Weird,Ohyeah,"   
tagToRemove = "Weird,"

Upvotes: 2

Views: 391

Answers (4)

Morv
Morv

Reputation: 390

Your problem is not the code itself but how the code was saved. Try using notepadd++ or something else to change the encoding and see what characters compose your code.

Get rid of strange chars as they will cause your javascript environment to raise that illegal token error.

Upvotes: -2

Luiz Carlos Faria
Luiz Carlos Faria

Reputation: 274

Change

var tagToRemove = item.name + ',';

to

var tagToRemove = new RegExp(item.name.toLowerCase() + ",", "gi");

Full example! https://jsfiddle.net/luizcarlosfaria/L8hph6hr/

Upvotes: 0

CupawnTae
CupawnTae

Reputation: 14580

You have an invisible ("zero-width space") character at the end of that line, making the line invalid. Note if you put your cursor after the semicolon and hit right then left, the cursor doesn't appear to move at all.

This can happen when you copy code around, particularly from certain websites.

You can just delete the offending character, or if you copy and paste the code below which looks identical but has been cleaned up, it will get rid of the error.

onDelete: function (item) {
    var existingTags = $('.lblTags').html();
    var tagToRemove = item.name + ',';
    var temp = existingTags.replace(tagToRemove, ''); // zero-width space removed here
    $('.lblTags').text(temp);
}

As per Andreas's comment, jsfiddle will display the offending character in red if you paste your code, shown here.

Upvotes: 4

ofir fridman
ofir fridman

Reputation: 2789

I try the problematic code u add and it work for me.

All u need to do is to remove the last char after the ";" this char is not visable

var temp = existingTags.replace(tagToRemove, '');​

Check the below code:

var existingTags = "Oddity,Strange,Weird,Ohyeah,";
var tagToRemove = "Weird,";

var temp = existingTags.replace(tagToRemove, '');

document.getElementById("result").innerHTML = temp;
   
console.log(temp);
<div id="result"></div>

Upvotes: -1

Related Questions