Repository.uobabylon.edu.iq



String Object in JavascriptStrings are simply groups of characters, like 'JavaScript', 'Hello world!', ' ' or even '14'. When you write JavaScripts, you need to know what strings are and how they work. You'll use them a lot, since most things you can read out (the URL of a page, a style sheet declaration, the value of a form field) are strings.When you declare and manipulate strings, always write them with single quotes ' or double quotes " around them. This tells the browser that it's dealing with a string. Don't mix up your quotes, if you start a string with a single quote and end it with a double quote, JavaScript doesn't understand what you mean. As a rule, I use single quotes ' because I've decided to use double quotes for HTML and single quotes for JavaScript. Let's introduce our two test strings that we'll use throughout this page:var a = 'Hello world!'; var b = 'I am a JavaScript hacker.'Now we have declared two variables, a and b and put strings in them. Having done this, we can start working with them. But first of all, a problem: suppose I'd writtenvar b = 'I'm a JavaScript hacker.';This string has a single quote in it, so JavaScript thinks that the string ends, doesn't understand what comes next and gives error messages. So you need to escape the single quote, telling the browser to treat the quote as a character, and not as a command to end the string. This is done by placing a backslash \ before it:var b = 'I\'m a JavaScript hacker.'Note that you can put double quotes in the string without escaping them. After all, you've defined the single quotes as the beginning and end of the string, sovar b = 'I\'m a JavaScript "hacker".'gives no problems. The double quotes are automatically treated as parts of the string, not as commands. If you want to change a string to a number, first make sure there are only the characters 0-9 in the string. var c = '1234'; d = c * 1;Since multiplying assumes numbers, JavaScript makes the string a number, if possible. If that isn't possible, the result is NaN. Note that you cannot dovar c = '1234'; d = c + 0;This would yield '12340' because JavaScript thinks the + means concatenate string, not add.to solve this problem you may need to use ParseInt() or ParseFloat() and to convert back to string you can do ToString()Manipulating the Object The String object is used to manipulate a stored piece of text. String objects are created with new String().Syntaxvar txt = new String("string"); // or more simply: var txt = "string";Examples of use:The following example uses the length property of the String object to find the length of a string:var txt="Hello world!";document.write(txt.length); //The code above will result in the following output: 12as we learnt before in OOPS , each object has a set of properties and a set of methods and as String is object , then it has the following :Properties :Constructor: Returns the function that created the String object's prototypelength : Returns the length of a string prototype: Allows you to add properties and methods to an objectExample of using Prototype :Use the prototype property to add a property to an object:function employee(name,jobtitle,born) {this.name=name;this.jobtitle=jobtitle;this.born=born; }function TestEmployee() {var fred=new employee("Fred Flintstone","Caveman",1970);employee.prototype.salary=null;fred.salary=20000;document.write(fred.salary);String Object Methodsconcat() Joins two or more strings, and returns a copy of the joined strings ,. This method does not change the existing strings, it only returns a copy of the joined strings.Syntaxstring.concat(string2, string3, ..., stringX)Examplevar str1="Hello ";var str2="world!";document.write(str1.concat(str2));The output of the code above will be:Hello world! The match() method searches for a match between a regular expression and a string, and returns the matches.This method returns an array of matches, or null if no match is found.Syntaxstring.match(regexp)Examplevar str="The rain in SPAIN stays mainly in the plain"; var patt1=/ain/gi;document.write(str.match(patt1));The output of the code above will be:ain,AIN,ain,ain replace() The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substringSyntaxstring.replace(regexp/substr,newstring)regexp/substr [Required]. A substring or a regular expression.Newstring[ Required]. The string to replace the found value in parameter 1Examplevar str="Visit University!";document.write(str.replace("University", "My House"));The output of the code above will be:My HouseNote You can perform REGEX Operations with this Method like performing a case-insensitive search:var str="Visit University!";document.write(str.replace("/university/i", "My House"));The output of the code above will be:My Houseslice() Extracts a part of a string and returns a new string ?The slice() method extracts a part of a string and returns the extracted part in a new string. Otherwise it returns -1.Syntaxstring.slice(begin,end)Examplevar str="Hello happy world!"; document.write(str.slice(0)+"<br />") ;// extract all characters, start at position 0document.write(str.slice(6)+"<br />"); // extract all characters, start at position 6document.write(str.slice(-6)+"<br />"); // extract from the end of the string, and to position -6document.write(str.slice(0,1)+"<br />"); // extract only the first characterdocument.write(str.slice(6,11)+"<br />");// extract the characters from position 6 to position 11The output of the code above will be:Hello happy world!happy world!world!Hhappy split() Splits a string into an array of substrings Syntaxstring.split(separator, limit)separator [Optional]. Specifies the character to use for splitting the string. If omitted, the entire string will be returnedlimit [Optional]. An integer that specifies the number of splitsExamplevar str="How are you doing today?";document.write(str.split("") + "<br />");document.write(str.split(" ",3));The output of the code above will be:H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?How,are,youNote : If an empty string ("") is used as the separator, the string is split between each character.substr() The substr() method extracts the characters from a string, beginning at "start" and through the specified number of character, and returns the new sub string.Syntaxstring.substr(start,length)Examplevar str="Hello world!";document.write(str.substr(3)+"<br />");document.write(str.substr(3,4));The output of the code above will be:lo world!lo wThere are some other straight-forward-use Methods with String Object such as :search() Searches for a match between a regular expression and a string, and returns the position of the match substring() Extracts the characters from a string, between two specified indices toLowerCase() Converts a string to lowercase letters toUpperCase() Converts a string to uppercase letters valueOf() Returns the primitive value of a String objectfromCharCode() Converts Unicode values to characters indexOf() Returns the position of the first found occurrence of a specified value in a string lastIndexOf() Returns the position of the last found occurrence of a specified value in a string match() Searches for a match between a regular expression and a string, and returns the matches charAt() Returns the character at the specified indexcharCodeAt() Returns the Unicode of the character at the specified indexString HTML Wrapper MethodsThe HTML wrapper methods return the string wrapped inside the appropriate HTML tag.anchor() Creates an anchorbig() Displays a string using a big fontblink() Displays a blinking string ( Works in FF and Safari Only)bold() Displays a string in boldfixed() Displays a string using a fixed-pitch fontfontcolor() Displays a string using a specified colorfontsize() Displays a string using a specified sizeitalics() Displays a string in italiclink() Displays a string as a hyperlinksmall() Displays a string using a small fontstrike() Displays a string with a strikethroughsub() Displays a string as subscript textsup() Displays a string as superscript textThe HTML Warpper Methods can be used directly in the form of String.Method() for example :Var x='Test Me';document.write(x.sup()); ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download