String

From PlainOldWebserver

Jump to: navigation, search

String()

String() is a deeper issue than you know, supporting many different languages and encodings.

First the obscure and trivial.


  var a = new String("Hello");
  document.writeln(a.bold().blink());


Here are the essential string functions.

  var words = "A fine day, indeed!";
  document.writeln(words);
  var m = words.match(/(\w{4})/);
  if(m) {
       document.writeln("match is "+m[1]);
  }
  words = words.replace(/(\w{4})/, "wet");
  document.writeln(words);
  var sep_words = words.split(/ /);
  for (var i in sep_words) {
       document.writeln(i+": "+sep_words[i]);
  }
  var sub = words.substring(2,5);
  document.writeln("Sub is '" +sub+"'");

Result:

  A fine day, indeed!
  match is fine
  A wet day, indeed!
  0: A
  1: wet
  2: day,
  3: indeed!
  Sub is 'wet'

One wonderful part of using substring() is that even in Chinese, the index '4' still refers to the fifth character, despite double-byte issues.

Personal tools
Navigation