Mark Needham

Thoughts on Software Development

Javascript: File encoding when using string.replace

with 3 comments

We ran into an interesting problem today when moving some Javascript code which was making use of the 'string.replace' function to strip out the £ sign from some text boxes on a form.

The code we had written was just doing this:

var textboxValue = $("#fieldId").val().replace(/£/, '');

So having realised that we had this code all over the place we decided it would make sense to create a common function that strip the pound sign out. These common functions reside in a different js file to the original code.

function Common() {
	this.stripPounds = function(value) {
		return value.replace(/£/, '');
	};
}

We replace the above code with a call to that instead:

var textboxValue = new Common().stripPounds($("#fieldId").val());

Having done this we realised that the £ sign was no longer being replaced despite the fact that the code was pretty much identical.

After a lot of fiddling around Brian eventually realised that the js file containing 'Common' was ANSI encoded when we actually needed it to be UTF-8 encoded, probably because we created it in Visual Studio.

As a result the £ sign is presumably being read as some other character which means the replacement doesn't happen anymore.

Converting the file to UTF-8 encoding fixed the problem for us but it's certainly not something I'd have ever thought of.

Written by Mark Needham

February 10th, 2010 at 12:02 am

Posted in Javascript

Tagged with

3 Responses to 'Javascript: File encoding when using string.replace'

Subscribe to comments with RSS or TrackBack to 'Javascript: File encoding when using string.replace'.

  1. File encoding has been the bane of my programming existence. Glad you guys got it figured out! Things like that eat up a tonne of time before you realize it's something small like encoding.

    Jordan Boesch

    10 Feb 10 at 6:30 pm

  2. You could instead make the stripPounds function a jquery function so that you can do:

    $("#fieldId").stripPounds().val()

    instead

  3. @Sarah yeh you're right that would be a better solution although we already have the pattern of putting that type of function in a common place so we thought we'd keep to that rather than writing an extension to jQuery.

    Mark Needham

    13 Feb 10 at 11:05 am

Leave a Reply