javascript regex, split user's full name - javascript

I have user's firstname and lastname in one string, with space between
e.g.
John Doe
Peter Smithon
And now I want convert this string to two string - firstname and lastname
John Doe -> first = John, last = Doe
John -> first = John, last = ""
[space]Doe -> first = "", last = Doe.
I am using next code
var fullname = "john Doe"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // Doe
and this works well for two-word fullname. But if fullname has one word, then I have problem
var fullname = "john"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // john
http://jsfiddle.net/YyCKx/
any ideas?

Use split + shift methods.
var parts = "Thomas Mann".split(" "),
first = parts.shift(),
last = parts.shift() || "";
So in case of single word name it will give you expected result:
last = "";

Use this code:
You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.
function splitFullName(a,b,c){
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
document.getElementById(c).oninput=function(){
fullName = document.getElementById(c).value;
if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
first = fullName.capitalize();;
last = "null";
}else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
last = fullName.substring(first.length +1,fullName.length).capitalize();
}else{
first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
}
document.getElementById(a).value = first;
document.getElementById(b).value = last;
};
//Initial Values
if(document.getElementById(c).value.length === 0){
first = document.getElementById(a).value.capitalize();
last = document.getElementById(b).value.capitalize();
fullName = first + " " + last ;
console.log(fullName);
document.getElementById(c).value = fullName;}}
//Replace the ID's below with your form's field ID's
splitFullName("firstName","lastName","fullName");
Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/

You can use split method
var string = "ad";
var arr = string.split(" ");
var last = arr[0];
var first = arr[1];
if(first == null){
first = "";
}
alert(last + "\n" + first)​;​

If in every situation you have just "first last" you could use:
var string = "john "
var i = string.split(" ");
alert("first: "+i[0]+ "\n"+ "last: " + i[1]);

I know that this has already been replied to and marked as answered but i just want to note that if you do still want to use regex you can change the "last" expression:
var last = string.replace(/^[a-zA-Z]*/, "").toUpperCase().trim();

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('#LastName').val(lastname);
});
});

var str='John';
var str2='Peter Smithon';
var str3='Peter';
var words=str.split(/\s+/g,2);
var first=words[0];
var last=words[1]||'';
alert(first+' '+last);

Related

Accessing an object not working with a variable

This seems simple but I'm banging against a wall. My code gets weights, accesses an object array to get a value then calculates a result using that value * weight. But accessing the object doesn't work with a variable.
function calc(){
var gender;
if(document.getElementById("male").checked){
gender = "mensList";
} else if (document.getElementById("female").checked){
gender = "womensList";
} else {
alert("Please select a gender");
return false;
}
var kg = parseInt(document.getElementById("bwKg").value);
var grams = parseFloat(document.getElementById("bwGrams").value);
var bw = parseFloat(kg + grams);
var lifted = parseFloat(document.getElementById("liftWeight").value);
var theValue = womensList[bw]; // This works
var theValue = mensList[bw]; // This also works
var theValue = gender[bw]; // This doesn't work
var theValue = gender + "[\"" + bw + "\"]" // Nor this
var result = theValue * lifted;
document.getElementById("result").textContent = result;
}
var womensList = {
40.0: "1.4936",
40.1: "1.4915",
40.2: "1.4894",
40.3: "1.4872",
40.4: "1.4851",
// ......... etc
150.7: "0.7691",
150.8: "0.7691",
150.9: "0.7691"
};
var mensList = {
40.0: "1.3354",
40.1: "1.3311",
40.2: "1.3268",
40.3: "1.3225",
40.9: "1.2975",
// ......... etc
205.7: "0.5318",
205.8: "0.5318",
205.9: "0.5318"
};
In your code you are setting a gender to string not variable.
if(document.getElementById("male").checked){
gender = "mensList";
} else if (document.getElementById("female").checked){
gender = "womensList";
}
Should be
if(document.getElementById("male").checked){
gender = mensList;
} else if (document.getElementById("female").checked){
gender = womensList;
}
Here is your problem :
if(document.getElementById("male").checked){
gender = "mensList"; //gender now contains a string only..
} else if
Since gender contains a mere string, this will not work:
var theValue = gender[bw]; // This doesn't work
What you should be doing instead is :
if(document.getElementById("male").checked){
gender = mensList; //now gender contains an array provided mensList is defined beforehand ..
}

Pull number value from string

So I need to pull a number value from a string. I currently have a working solution but I feel that maybe I can improve this using a regular expression or something.
Here is my working solution
var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}
As you can see I'm trying to pull the number value from after the "[REF: " string.
// Change of the text for better test results
var subject = "hjavsdghvwh jgya 16162vjgahg451514vjgejd5555v fhgv f 262641hvgf 665115bs cj15551whfhwj511";
var regex = /\d+/g;
let number = subject.match( regex )
console.log(number)
It Will return array for now, and if no match found, it will return null.
For most of the time, when i used this regex i get perfect result unless if string contains decimal values.
var str = 'This is a test message [REF: 2323232]'
var res = str.match(/\[REF:\s?(\d+)\]/, str)
console.log(res[1])
If you don't want to use a regular expression (I tend to stay away from them, even though I know they are powerful), here is another way to do it:
// Your code:
/*var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}*/
// New code:
const subject = "This is a test message [REF: 2323232]";
const codeAsString = subject.split('[REF: ')[1]
.split(']')
.join('');
if (!isNaN(parseInt(codeAsString))) {
console.log('Valid ticket number: ', parseInt(codeAsString));
}
else {
console.log('Invalid ticket number: ', codeAsString);
}
This will extract number
var subject = "This is a test message [REF: 2323232]";
var onlyNum = subject.replace(/.*(:\s)(\d*)\]$/,'$2');
console.log(onlyNum)
Here, same but the number is now a real int
var subject = "This is a test message [REF: 2323232]";
var onlyNum = parseInt(subject.replace(/.*(:\s)(\d*)\]$/,'$2'));
console.log(onlyNum)

Array issues (javascript)

I created a small function that stores the book isbn, it's name and it's author. Everything is fine until I start to print out array. On every entery that completes the object into array, I want it to be printed one after another in new row, but this one is printing the objects from beginning every time when a new object is inserted. How do I fix this?
var books = [];
function blaBla(){
while(isbn != null || name != null || writer != null){
var isbn = window.prompt("Enter ISBN");
var name = window.prompt("Enter name of the book");
var writer = window.prompt("Enter name of the writer");
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
if(isbn.match(patternNum)){
if(name.match(patternString)){
if(writer.match(patternString)){
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
}
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}
}
PS: How do I make it even more "cleaner", so when I hit cancel on prompt, it automatically stops with entering data into array, while, if i stop it on the "writer" prompt, it deletes previous entries for that object (last isbn and last name of the book)?
Thanks in advance.
You might want to give a little more context as to what this function is doing so we can help make your code cleaner as requested. I've separated the collection logic from the display logic here, and also used a while (true) loop with breaks on null or invalid inputs which will stop the collection of data.
Please note that prompt/alert boxes are a hideous way of collecting user input though (very awkward user experience). Consider using a table, input fields, and some jQuery instead to add rows and validate what the user has entered into input boxes.
var books = [];
function collectResponses() {
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
while (true) {
var isbn = window.prompt("Enter ISBN");
if (!isbn || !isbn.match(patternNum)) {
break;
}
var name = window.prompt("Enter name of the book");
if (!name || !name.match(patternNum)) {
break;
}
var writer = window.prompt("Enter name of the writer");
if (!writer || !writer.match(patternNum)) {
break;
}
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
function displayResponses() {
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}

how can i make this jsonArray form?

I want to get this (four keys & values in one object):
[{"sms":"Y","email":"Y","phone":"Y","oto":"Y"},{"sms":"N","email":"N","phone":"N","oto":"N"}]
but this is result :
[{"sms":"Y"},{"email":"Y"},{"phone":"Y"},{"oto":"Y"},{"sms":"N"},{"email":"N"},{"phone":"N"},{"oto":"N"}]
here is my code:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk = 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});
Can you please show us the form as well? This gives a limited scope to answer.
But If i guess right, you have a form wherein you have the following fields sms, email, phone, and then oto, right?
So what you have to do is, instead of doing it for each input, you have to do it once for the four inputs.
Meaning that you have to set chkObj['sms'], chkObj['email'], chkObj['phone'], and then chkObj['oto'] and then do chkArray.push(chkObj).
You missed the second equals sign in this expression:
if(cntchk = 4){, so instead of comparison there is an assignment. Change this to if(cntchk == 4){
You have missed one "=" sign in if condition.
try this:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk **==** 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});

Assigning initial values using the with statement

The following works:
var Person = {};
Person.FirstName = '';
Person.LastName = '';
with (Person) {
FirstName = 'Phillip',
LastName = 'Senn';
}
log(Person);
But I want to remove lines 2-3.
What about:
var Person = {FirstName:'Philip', LastName:'Senn'};
log(Person);

Categories