I'm trying to catch a person's name. The name would be entered in a text box such as:
my name is Robert or yes my name is Robert etc.
I don't know where the actual name will fall however because of intro words etc.
I was thinking something like this.
I search for "my name is"
I capture it in an array
I split the array
I now know the actual name follows as such:
namesParts[0] - would be "my"
namesParts[1] - would be "name"
namesParts[2] - would be "is"
namesParts[3] - would be the name i'm looking for.
Something perhaps like the below but this doesn't work.
if (input.search("my name is")!= -1) {
var names = input.match(/my name is/);
var namesParts = names.split(' ');
var one = namesParts[3];
document.result.result.value = "Ok your name is "+one+".";
return true;
}
If all other words will start with lower case letter you could use
'my name is Robert'.match(/[A-Z]+\w*/);
otherwise
'My name is Robert'.match(/my name is (\S+)/i);
Check the JavaScript String.split Method.
Examples:
var str="my name is Robert";
var n=str.split('my name is ');
alert('1. Length: '+n.length +' Array: '+ n);
var str="my name is Robert";
var n=str.split(' ');
alert('2. Length: '+n.length +' Array: '+ n);
var str="my name is Robert";
var n=str.split('');
alert('3. Length: '+n.length +' Array: '+ n);
Live example: http://jsfiddle.net/a4D8q/
Related
var first = "a whole lotta stuff";
var second = "first";
document.querySelector("input").value = second;
right now the value of the input will be "first". I want it to be "a whole lotta stuff".
in other words, I want the value of the input to be the var first and not just a string of "first".
Based on the additional information you provided in your comment:
var nameNum = "name" + productNum;
document.querySelector("[name=name]").value = nameNum;
//there are vars name1, name2, etc..
//when I ran it I got value="name2"
You need change the way you try and access the variables name1, name2, etc.
The solution is to nest name1 and name2 inside an object and access the keys by building the string within bracket notation. Like this: names['name' + productNum];
Check out this example:
var names = {
name1: 'foo',
name2: 'bar',
}
var productNum = 2
document.querySelector('input').value = names['name' + productNum];
<input type="text">
I removed double quotes around first in second line.
var first = "a whole lotta stuff";
var second = first;
document.querySelector("input").value = second;
Including double quotes makes "first" a string that is assigned to second. Without quotes first is a reference and the value of first is assigned (copied) to second.
I have a variable consisting of multiple sentences separated with dots named var a. Then I want to check if Result value is equal to one of the sentences on var a:
Here is the code:
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var nameSplit = a.split(".");
console.log(nameSplit.length);
console.log(nameSplit);
var Result = "his name is mike";
var i;
for (i = 0; i < nameSplit.length; i++) {
if (nameSplit[i].includes(Result)) {
console.log("Result is one of the sentences on var a");
}
}
The code works fine .
The problem is I have no idea if this code works fast and efficient if I have 1000 sentences or 10000 sentences on var a?
Is there any modification that makes the code faster to execute?
Is there any better solution to do this?
You can use Array.prototype.includes to check if an array includes a string. or String.prototype.includes to match a substring.
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var nameSplit = a.split(". ");
var Result = "his name is mike";
nameSplit.includes(Result) // true
or
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var Result = "his name is mike";
a.includes(Result) // true
You need to ask yourself how many substring you want to find in a, if just one, then you dont need to split as split itself takes time and space. (If interested , you can further check KMP algorithm which can efficiently match word W in a string S.)
If you have a huge amount of substrings to be matched, you then can use split, which costs more space to trade off time.
I think the fastest way should be with
str.indexOf('his name is mike') !== -1
but for 1k words i dont think its relevant
Your question says you "want to check if Result value is equal to one of the sentences" but your code doesn't check for equality. It allows partial matches — for example if Result is i it matches the i in my name is jack..
If you want to match the whole sentences, you could split the sentences into a Set and then checking for matches is a constant time operation. But they'll need to be exact matches, including whitespace.
var a = "my name is jack. your name is sara. her name is joe. his name is mike";
var nameSplit = new Set(a.split(/\.\s+/g))
var Result = "his name is mike";
if (nameSplit.has(Result)) {
console.log("Result is one of the sentences on var a");
}
Result = "his name is";
if (nameSplit.has(Result)) {
console.log("Result is one of the sentences on var a");
} else {
console.log("not in sentences")
}
I have an assessment for Java script basics that I have not been able to study for due to unforeseen circumstances so I am now having to catch up in the little time I have.
My assessment states that I must find the substring of the start of each string, which I have managed to do but I am having trouble joining those two processed substrings into the one alert box ( I know these are frowned upon but the assessment states I must use this). I have tried using the + operator but this gives me the error of the second variable being produced twice. I have posted my code below for anyone to have a look.
function userName(){
var name = "Joe";
var surName = "Bloggs";
name = name.substring(0,1);
surName = surName.substring(0,1);
alert(name);
}
function userName(){
var name = "Joe";
var surName = "Bloggs";
name = name.substring(0,1);
surName = surName.substring(0,1);
alert(name + surName );
}
Basically you can concat two variables (strings) using the + operator. The type of htese variables are defined dynamically and the + operator will concat them into a single variable (string), after that you can show the result into a alert.
function userName()
{
var name = "Joe"
var surName = "Bloggs"
name = name.substring(0,1)
surName = surName.substring(0,1)
var result = name + surName;
alert(result);
}
On the other hand, to get only the first char of a string variable in javascript, you can treats it as a array of chars and access the first index, (starting in 0) for sample:
function userName()
{
var name = "Joe"
var surName = "Bloggs"
var result = name[0] + surName[0]; // get only the first char
alert(result);
}
Alternativelly, there a method called string.concat(string) which allows you to concat two strings.
String concatenation This is a very discussed question in many languages and I recommend you to read this thread on stack overflow:
Best way to concatenate strings in JavaScript?
Have you tried
alert(name + ' ' + surname)
This is just joining to strings with the a space ' '
This question already has answers here:
Split First name and Last name using JavaScript
(26 answers)
Closed 7 years ago.
I am having a hard time chaining some methods together. Can you please provide some assistance?
The end result should = Mickey MOUSE
var name = "MicKEy MOUse";
function nameChanger(oldName) {
var finalName = oldName;
var splitString = name.split(' ');
var fname = splitString.slice(0,1);
var fname_lower = fname.toLowerCase.slice(1,6);
return fname_lower;
};
console.log(nameChanger(name));
Since I am trying to learn the methods in the function I would appreciate assistance on those items. However, if there are more eloquent ways of performing the same action I would appreciate that input as well.
Thank you in advance for your knowledge and direction.
Split the name into two, based on the space character
var splitString = oldName.split(' ');
Convert the entire first string to lowercase and the second string to uppercase.
var fname = splitString[0].toLowerCase();
var lname = splitString[1].toUpperCase();
Now, just create a new String from fname, by changing the first character to upper case, join it with lname and return it, like this
return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
So, your complete function would look like this
function nameChanger(oldName) {
var splitString = oldName.split(' ');
var fname = splitString[0].toLowerCase();
var lname = splitString[1].toUpperCase();
return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
};
Note: You might be wondering, why we are doing this
fname[0].toUpperCase() + fname.substring(1)
to change just the first character of fname. In JavaScript, Strings are immutable objects. Once a String object is created, it can never be changed. So, we are creating a new String object, based on the modified first character of fname and the rest of fname.
var name = "MicKEy MOUse";
function nameChanger(oldName) {
var splitString = name.split(' ');
return splitString[0].charAt(0).toUpperCase()+splitString[0].slice(1).toLowerCase()+' '+splitString[1].toUpperCase();
};
console.log(nameChanger(name));
Expanded code (for Robert Rossmann):
var name = "MicKEy MOUse";
function nameChanger(oldName) {
//Splitting `oldName` to array with words
var splitString = name.split(' ');
//Setting variable which contains first word
var firstWord = splitString[0];
//Setting variable which contains second word
var secondWord = splitString[1];
//Setting variable which contains first letter of first word
var firstWordLetter = firstWord.charAt(0);
//Setting variable which contains first word letters, without first letter
var firstWordRestOfLetters = firstWord.slice(1);
//Result first word (first letter to upper case, rest of letters to lower case)
var resultFirstWord = firstWordLetter.toUpperCase()+firstWordRestOfLetters.toLowerCase();
//Result second word (all second word letters to upper case)
var resultSecondWord = secondWord.toUpperCase();
//Returning string with first and second word separated with space
return resultFirstWord+' '+resultSecondWord;
};
I have the following code as part of a table sorting script. As it is now, it allows names in the "FIRST LAST" format to be sorted on LAST name by "reformatting" to "LAST, FIRST".
var FullName = fdTableSort.sortText;
function FullNamePrepareData(td, innerText) {
var a = td.getElementsByTagName('A')[0].innerHTML;
var s = innerText.split(' ');
var r = '';
for (var i = s.length; i > 0; i--) {
r += s[i - 1] + ', ';
}
return r;
}
It currently seems to sort on the name after the LAST space (ex. Jean-Claude Van Damme would sort on 'D').
How could I change this script to sort on the FIRST space (so Van Damme shows up in the V's)?
Thanks in advance!
Instead of the .split() and the loop you could do a replace:
return innerText.replace(/^([^\s]+)\s(.+)$/,"$2, $1");
That is, find all the characters up to the first space with ([^\s]+) and swap it with the characters after the first space (.+), inserting a comma at the same time.
You can shorten that functio a bit by the use of array methods:
function FullNamePrepareData(td, innerText) {
return innerText.split(' ').reverse().join(', ');
}
To put only the first name behind everything else, you might use
function FullNamePrepareData(td, innerText) {
var names = innerText.split(' '),
first = names.shift();
return names.join(' ')+', '+first;
}
or use a Regexp replace:
function FullNamePrepareData(td, innerText) {
return innerText.replace(/^(\S+)\s+([\S\s]+)/, "$2, $1");
}
I don't know where the sorting happens; it sounds like you just want to change the reordering output.
The simplest would be to use a regexp:
// a part without spaces, a space, and the rest
var regexp = /^([^ ]+) (.*)$/;
// swap and insert a comma
"Jean-Claude Van Damme".replace(regexp, "$2, $1"); // "Van Damme, Jean-Claude"
I think you're after this:
var words = innerText.split(' '),
firstName = words.shift(),
lastName = words.join(' ');
return lastName + ', ' + firstName;
Which would give you "Van Damme, Jean-Claude"