Reputation: 921
I have got a text area and a function that splits the pasted content based on the spaces between content elements and turns them into labels one by one:
Say I have the following content to be pasted:
1234,john smith,[email protected] 4312,jack gold,[email protected] 5678,Brian,[email protected]
and obviously I use
$('#testArea').on("paste", ".maininput", function (event) {
var text = $(element).val();
var contentArray = text.split(" ");
}
The result should be 3 labels with the following format (users mobile number,full name, email)
But because of the fact that there are spaces between firstname and lastname I am not able to get the right result.
What I am trying to achieve is sort of escaping the spaces when its between first and last name.
has anyone got any idea how to do it?
Upvotes: 0
Views: 142
Reputation: 19
jQuery( window ).load(function() {
jQuery("#FullNametest").change(function(){
var temp = jQuery(this).val();
var fullname = temp.split(" ");
var firsname='';
var middlename='';
var lastname = '';
firstname=fullname[0];
lastname=fullname[fullname.length-1];
for(var i=1; i < fullname.length-1; i++)
{
middlename = middlename +" "+ fullname[i];
}
jQuery('#FirstName').val(firstname);
jQuery('#middlename').val(middlename);
jQuery('#LastName').val(lastname);
});
});
Upvotes: 0
Reputation: 303205
Don't split on spaces. Instead, scan for what you want:
var s = "1234,john smith,[email protected] 4312,jack gold,[email protected] 5678,Brian,[email protected]"
var lines = s.match(/\S[^,]+,[^,]+,[^ ]+/g)
for (var i=lines.length;i--;){
console.log(lines[i].split(','));
}
// ["5678", "Brian", "[email protected]"]
// ["4312", "jack gold", "[email protected]"]
// ["1234", "john smith", "[email protected]"]
That regex says:
Upvotes: 4
Reputation: 207501
Better to use a regular expression to match the pattern.
var str = "1234,john smith,[email protected] 4312,jack gold,[email protected] 5678,Brian,[email protected]";
var matchGroups = str.match(/([^,]*,[^,]*,[^ ]*)/g); //look for pattern "XXX,XXX,XXX" followed by whitespace or end of line
console.log(matchGroups);
//Now work with the sections
for( var i=0;i<matchGroups.length;i++){
var parts = matchGroups[i].split(","); //split it into your parts on commas
console.log(parts);
}
Upvotes: 1
Reputation: 10003
For example, replace <space><digit>
with |<digit>
and then split on |
:
text.replace(/ (\d)/g, "|$1").split("|")
Example:
"1234,john smith,[email protected] 4312,jack gold,[email protected] 5678,Brian,[email protected]".replace(/ (\d)/g, "|$1").split("|")
["1234,john smith,[email protected]",
"4312,jack gold,[email protected]",
"5678,Brian,[email protected]"]
Upvotes: 0
Reputation: 4249
you can run a for loop to check the next character of space, and based on it you can replace space with
or leave it as it is. I mean if the next character is a number you can simply leave the space as it is and if it is a letter change space to
Upvotes: 0