JavaScript Data Structures - The String Object
Written by Ian Elliot   
Thursday, 17 January 2019
Article Index
JavaScript Data Structures - The String Object
Characters
String manipulation

String manipulation

Joining strings

Working with strings in JavaScript is very easy. You can join two strings together using either the concatenation operator + or the concat method. For example:

var s3=s1+s2;

joins s1 to s2 and stores the result in s3 as does

var s3=s1.concat(s2);

Substrings - slice, substr and substring

If you need to extract a substring you can use either slice or substr - the only differ in how the substring is specified.

The slice method uses a begin and end location

s1.slice(b,e);

returns the string starting a character b in s1 and up to but not including character e. For example:

var s1 = "ABCDEFG";
alert(s1.slice(1,3));

Displays "BC" i.e. characters 1 and 2 but not 3. You can leave out the end specification and the end of the string will be assumed. You can also use a negative index to select from the end of the string. For example:

var s1 = "ABCDEFG";
alert(s1.slice(1));
alert(s1.slice(1,-2));

displays "BCDEFG" and "BCDE".

The substr method used a start and length specification. That is, substr(s,n) returns the substring starting at s and with at most n characters. For example

var s1 = "ABCDEFG";
alert(s1.substr(1,3));

displays "BCD", i.e. starting at character 1 and 3 characters.

To confuse matters there is also a substring method which appears to work in the same way as slice. It does but there are some minor differences in behaviour that can cause problems.

slice(s,e) and substring(s,e) are different in two ways:

  • you can't use negative values in substring it treats them as 0.
  • if s>e then substring will swap them over but slice doesn't and returns a null string.

Replace a substring

If you want to replace part of a string with a new string you can use the replace method:

replace(target,newstring)

this searches the string for the target string and replaces it with the newstring. For example:

var s1 = "ABCDEFG";
alert(s1.replace("CD", "XXX"));

results in "ABXXXEFG". There is a more complicated and flexible version of replace that uses a regular expression but this is beyond the scope of this article - look out for a future one on regular expressions.

Finding substrings

If you want to find one string in another use the indexOf(target,start) method. This will search the string starting at start and return the position of the first match for target or -1 is there is no match. For example:

var s1 = "ABCDEFG";
alert(s1.indexOf("CD",0));

searches the whole string and returns 2. If you leave out the starting location the whole string is searched.

The lastIndexOf(target,start) works in the same way but it searches from the end of the string back to the start location.  For example:

var s1 = "ABCDEAFG";
alert(s1.indexOf("A"));
alert(s1.lastIndexOf("A"));

displays 0 and 5.

There is also the search method that will find the location of the first match of a regular expression - as before this is beyond the scope of this article. There is also a match method that returns an array of multiple matches if there are any.

Strings and Arrays

The split method is particularly useful in that it can be used to convert a string into an array of words or substrings based on a delimiter. The method split(delimiter,limit) will split the string on each occurrence of the delimiter and stop once it has limit array elements. For example:

var s1 = "AB-DE-AFG";
alert(s1.split("-"));

returns an array with three elements consisting of "AB", "DE" and "AFG".  You can also use a regular expression as the delimiter specification and so break up the string based on multiple separating characters - as before this needs a full understanding of regular expression so look out for a later article.

You can also join up a set of strings stored in an array using the Array object's join method. You can even specify a separator string to be placed between each of the elements. For example:

var s1 = "AB-DE-AFG";
var a=s1.split("-");
var s2 = a.join("-");

This first splits the string apart into different array elements and then puts them back together using the same separator, with the result that s2 is the same as s1.

Upper and Lower

There are a few useful utility methods that don't really fit into a grand classification. For example there is the toLowerCase and toUpperCase methods which do exactly what their name suggests. However we also have the toLocaleLowerCase and toLocaleUpperCase which do the same tasks but taking into account the hosts current locale.

As string comparisons, e.g. s1==s2 or  s1===s2, are case sensitive, one use for toLowerCase (or toUpperCase) is to make comparisons case insensitive. That is:

s1.toLowerCase()==s2.toLowerCase()

is true is s1="ABC" and s2="abc".

HTML Wrappers

Finally we have the HTML methods which can be used to wrap a string in standard HTML tags. For example:

s2=s1.big();

returns a string in s2 that has the tag <big> added to its front and </big> to its end. These are useful and very obvious in use. In practice they are usually insufficient for what you want to do when manipulating or generating HTML.

Conclusion

There are some other string functions, such as Trim, which aren't standard enough to be relied upon and the temptation is to add custom methods to the String object. The best advice is don't do this. It is safer to follow the rule of not modifying an object you don't own. A much better solution is to create your own string object based on the String object and add methods and properties to it. 

 


JavaScript Data Structures 

Cover

Contents

  1. The Associative Array
  2. The String Object
  3. The Array object
  4. Speed dating - the art of the JavaScript Date object
  5. Doing JavaScript Date Calculations
  6. A Time Interval Object
  7. Collection Object
  8. Stacks, Queue & Deque
  9. The Linked List
  10. A Lisp-like list
  11. The Binary Tree
  12. Bit manipulation
  13. Typed Arrays I
  14. Typed Arrays II
  15. Master JavaScript Regular Expressions
    * First Draft
 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

kotlin book

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:0596517742>

<ASIN:0596806752>

 



Last Updated ( Thursday, 17 January 2019 )