JavaScript中字符串的替換方法

 JavaScript中的replace()方法只能替換查找到的第一個字符串,今天正好用到,google了一下,發現這樣一個函數,可以代替replace使用
  1. function replaceSubstring(inputString, fromString, toString) {
  2.  var temp = inputString;
  3.  
  4.  if (fromString == ""
  5.  {
  6.  return inputString;
  7.  }
  8.  
  9.  if (toString.indexOf(fromString) == -1) 
  10.  { 
  11.  while (temp.indexOf(fromString) != -1) 
  12.  {
  13.  var toTheLeft = temp.substring(0, temp.indexOf(fromString));
  14.  var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
  15.  temp = toTheLeft + toString + toTheRight;
  16.  }
  17.  } 
  18.  else 
  19.  { 
  20.  var midStrings = new Array("~""`""_""^""#");
  21.  var midStringLen = 1;
  22.  var midString = "";
  23.  while (midString == ""
  24.  {
  25.  for (var i=0; i < midStrings.length; i++) 
  26.  {
  27.  var tempMidString = "";
  28.  for (var j=0; j < midStringLen; j++) { tempMidString += midStrings; }
  29.  if (fromString.indexOf(tempMidString) == -1) 
  30.  {
  31.  midString = tempMidString;
  32.  i = midStrings.length + 1;
  33.  }
  34.  }
  35.  } 
  36.  while (temp.indexOf(fromString) != -1) 
  37.  {
  38.  var toTheLeft = temp.substring(0, temp.indexOf(fromString));
  39.  var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
  40.  temp = toTheLeft + midString + toTheRight;
  41.  }
  42.  while (temp.indexOf(midString) != -1) 
  43.  {
  44.  var toTheLeft = temp.substring(0, temp.indexOf(midString));
  45.  var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
  46.  temp = toTheLeft + toString + toTheRight;
  47.  }
  48.  } 
  49.  return temp; 
  50.  }

使用方法:
replaceSubstring("hello xx", "xx", "world") = "hello world"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章