Showing two .substring in the same alert() - javascript

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 ' '

Related

Outputting first letter of last name as well as both initials in Uppercase in Javascript console?

I'm a new student and having loads of problems with this exercise. Basically we need to write a function that gets a first and last name from the user (separated by a space) and output it into the console. We need to write 3 different functions, one to output first letter of first name original case, one first letter of last name original case, and a third output of both initials upper case. I've got the first one down but don't understand the split function well enough to get the other two it's driving me nuts. here is what i have thus far:
function GetText(promptMessage){
let x = prompt(promptMessage);
return x;
}
function Initials(FirstName, LastName){
text = Firstname.charAt(0);
return text;
}
text =GetText("Enter your name here");
let Firstname = text;
console.log(Initials(text));
function LastInitial(FirstName, LastName){
var names = string.split(' ');
return names;
}
var names;
var LastName = LastInitial(LastName);
console.log(LastName);
I basically have no idea how to write the second function and have just been moving the names around hoping to get it to work lol. haven't even started the Uppercase one... Please help !! thanks so much
The split() method returns an array of all the elements so to target the second element just do string.split(' ')[1]
Below you can find the full code:
function firstInitial(string) {
return string.charAt(0);
}
function lastInitial(string) {
return string.split(" ")[1].charAt(0);
}
function bothInitials(string) {
return (firstInitial(string) + lastInitial(string)).toUpperCase();
}
let name = prompt("Enter a name");
console.log(firstInitial(name));
console.log(lastInitial(name));
console.log(bothInitials(name));

JavaScript: string Manipulation [duplicate]

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;
};

How do I match a string that is not preceeded by a character?

I have an array of strings and I need to perform a search and replace on them using JavaScript. The issue is they only need to be found when they are not preceeded by one of two characters. What I have tried is:
var searchString = new RegExp( "(?<![#\|])" + tableName,"");
if(theLine.search(searchString) != -1){do something;}
tableName is variable and changes for each call based on data retreived from a database.
If tableName is Fred, I want to find Fred but not #Fred or |Fred.
What I have doesn't work and I'm not sure why. It's probably a simple goof but I don't see it.
var s = 'If tableName is Fred, I want to find Fred but not #Fred or |Fred';
s.match(/[^#\|]Fred/g)
[" Fred", " Fred"]
Though my answer contains an Extra Space. You need to do is
var s = 'If tableName is Fred, I want to find TFred Fred but not #Fred or |Fred';
var replaceWith = "XXXX";
s.replace(/[^#\|]Fred/g, function($1) {
if($1 != $1.trim()) {
return " " + replaceWith;
} else {
return replaceWith;
}
})
//output - "If tableName is XXXX, I want to find XXXX XXXX but not #Fred or |Fred"
JavaScript regex engine doesn't support lookbehinds. But you can do something like this regex to overcome that issue:
var s = 'If tableName is Fred, I want to find Fred but not #Fred or |Fred';
var r = s.replace(/([#|]Fred)|Fred/g, '$1')
//=> If tableName is , I want to find but not #Fred or |Fred
var searchString = new RegExp("(?<![^\|\#])" + tableName,"");
if (theLine.search(searchString) != -1){do something;}
You forgot to negate the character range that you don't want it to match on.

Select first complete string matching partial string

I have a page which contains many tags with a string in them, for example 'Am I a String? Yes'.
Using JQuery, I want to get the first instance of 'Am I a String? ' and then take the Yes or No after that and store it so I can use it in a conditional.
Any ideas?
Thanks.
The code I'm going with:
function experimentThree() {
var stringBool = $('*:contains("Was it enough? ")');
console.log('stringBool = : ' + stringBool);
console.log('stringBool Object 1 = : ' + stringBool[0]);
}
Thinking if I can get the complete string in the first object I can compare that to what I expect to see.
check this out
$('body').find('*:contains("Am I a String")').each(function(index, crntNode){
var parts = $(crntNode).text().split('?');
var flag = parts[1].trim();
alert(flag);
});
for example:
var a = $('div').text().match(/Am I a String\? (Yes|No)/g)[0];
var b = a.match(/(Yes|No)/g)[0];

Javascript - catch name in variable string

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/

Categories

Resources