Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, May 6, 2014

Strictness of Javascript

            Although  Javascript warning can be ignored, its a good practice to ensure that your code does not throw any warnings. This also ensures the quality of code. You can set the strict mode in Firefox as:

  • Type about:config in Firefox adressbar
  • Search word "strict" 
  • double click line that says : javascript.options.strict. This should set its value to true.

Thursday, October 18, 2012

Replacing Enter Key/Carraige return with br tag

When data is saved from a textArea and the data contains carriage returns(Enter key) then if the data is displayed in a text area in another form it will display properly.

However, if you try and display the same text/data as a normal html it will display it but will not consider the carriage returns and all the data will be displayed in a single line.

This can be achieved by:
var data=//get data from the text area
data=data.replace(/\r\n|\r|\n/g,"<br /> ");

now this data can be displayed as html

Wednesday, September 12, 2012

trim() function does not work in IE

For IE the trim function is not built into the String Object. So if you try to do something like:
var str="Hello  ";
str.trim()

IE will throw an error like “Object doesn’t support this property or method”.

Here is the fix for that:


// Adding trim function to String object
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

The code above first checks if trim function is available in the String Object. we need to check this because trim function is available for Firefox and Chrome.

The above code needs to be executed before you call the first trim function.