Thursday, December 11, 2014

JavaScript, convert object to number, replace part of string, trim




In JavaScript, Number function is used to  convert different object values to their numbers:

For example
var x4 = "9";
var x5= "9";
alert(x4+x5);
alert(Number(x4)+Number(x5);

 alert(x4+x5) produces 99, while alert(Number(x4)+Number(x5) produce 18.

In JS, to replace part of string
var str = "Visit Vancouver!";
var res = str.replace("Vancouver", "Seattle");


This just replace first occurrence of  Vancouver, to replace all Vancouver to Seattle
var res = str.replace(/Vancouver/g, "Seattle");


JS function trim will remove whitespace from both sides of a string:
Example:
var str = "       Hello World!        ";
alert(str.trim());



No comments:

Post a Comment