What I am trying to get here is, i have a text field with no max length.
It can have single text or comma separated text. I want to get a regex, or way to cater for single or comm开发者_如何学Ca separted values and remove commma, if it's after last text and finally put the results in javascript array.
Example:
- Scenario #1: Textfield: abcdef
- Scenario #2: Textfield: abcd1, werwe23 ,hfghf,2345,sedwe
- Scenario #3: Textfield: abcd1, werwe23, hfghf,2345,sedwe, (by mistake of user).
Here's my sample code so far which caters for the ones with comma.
A suggestion with regex will help my cause.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> Get values </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<script type="text/javascript">
function getValues()
{
var val = document.getElementById("txtInput").value;
var splitted = val.split(',');
alert("splitted: "splitted);
}
</script>
</head>
<body>
<input type="text" id="txtInput"/>
<input type="button" onclick="javascript:getvalues();" value="get values"/>
</body>
</html>
Thanks
Use a regular expression to remove any trailing commas or whitespace before splitting:
val = val.replace(/[,\s]+$/, '');
In your code:
> alert("splitted: "splitted);
should be:
alert("splitted: " + splitted);
and
> <input ... onclick="javascript:getvalues();" ... />
should be:
<input ... onclick="getvalues();" ... >
the javascript:
part is read as a usless label.
精彩评论