如何解析和形成字符串以使用Javascript打开它的网页

时间:2011-03-07 17:58:08

标签: javascript string parsing forms

我有一个表单,我需要运行一些javascript来解析存储在表单中的页面信息以打开它。

<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}

function open()
{
     if (validateForm()) {
         1. get the value 
         2. parse the value to get year/month/date (?)
         3. compose the string of webpage (?)
         4. open the webpage (?)
     }
}
</script>

<form name="myForm" onsubmit="return open()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

输入的格式为2011/03/05,我需要打开http://abc/def/2011/03/2011_03_05.html。它需要解析日期,并附加字符串,然后打开页面。

ANSWER

<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
  return true;
}

function openPage()
{   
     if (validateForm()) {
        var value = document.forms["myForm"]["fname"].value

        var strYear = value.substring(0,4);
        var strMonth = value.substring(5,7);
        var strDay = value.substring(8,10);

        var strURL = "http://abc/def/"+strYear+"/"+strMonth+"/"+strYear+"_"+strMonth+"_"+strDay+".html";
        alert("strURL");

        //document.location.replace(strURL)
        //document.write(strURL);
        window.open(strURL,"myWindow");
     }
}
</script>

<form name="myForm" onsubmit="openPage()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

1 个答案:

答案 0 :(得分:2)

假设输入的格式始终为yyyy / mm / dd,您可以按如下方式解析字符串:

var strYear = fname.value.substring(0,4);
var strMonth = fname.value.substring(5,7);
var strDay = fname.value.substring(8,10);

var strURL = "http://abc/def"+strYear+"/"+strMonth+"/"+strYear+"_"+strMonth+"_"+strDay+".html";

// To change the same page with new URL, use:
  document.location.replace(strURL);
// To open a new popup window, use:
 window.open(strURL,"myWindow");