JavaScript: string Manipulation [duplicate] - javascript

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

Related

Javascript Regex - match int after string in for loop

I am trying to capture the counts associated with the keywords in the string txt. All the keywords are loaded into an array ahead of time.
This code is in jquery/javascript. I cannot hard code string keywords so that is why they are stored in an array. Please assist me in finding what goes in place of "Reg Expression" before and/or after the keyword variable within the loop.
The html br can be used to end that regexmatch in that iteration of the loop.
Trying to end up with keywordCount = "2, 5, 11"
//String I need to search through
var txt = "Edit Req'd2<br>Errors5<br>Pndg App11<br>";
//array of keywords I can use to find associated counts to keywords
var keyword = ["Edit Req'd", "Errors", "Pndg App"];
//empty string declared before loop
var keywordCount = '';
for (i = 0; i < keyword.length; i++) {
// takes the comma off end of first entry in array
// might not be needed or another method might be better?
keyword[i] = $.trim(keyword[i]);
//regex expression generated using keyword and unknown expression
var regexmatch = RegExp("Reg Expression" + keyword + "Reg Expression")
//use regex expression to generate string containing counts
keywordCount += (txt.match(regexmatch)) + ",";
}
Here is the example which may helps you in achieving your required output.
//String I need to search through
var txt = "Edit Req'd2<br>Errors5<br>Pndg App11<br>";
//array of keywords I can use to find associated counts to keywords
var keyword = ["Edit Req'd", "Errors", "Pndg App"];
//empty string declared before loop
var keywordCount = '';
var i = 0;
var keywordCount = "";
var splittedValue = "";
while (i < keyword.length) {
if (txt.indexOf(keyword[i]/i)) {
splittedValue = txt.split(keyword[i]);
if (keywordCount === "") {
keywordCount = splittedValue[1].split("<br>")[0];
} else {
keywordCount += ", " + splittedValue[1].split("<br>")[0];
}
}
i += 1;
}
console.log(keywordCount);
I would use a digit/numeric range to match the number ([0-9]; this is pretty basic regex stuff), and use a group to match any of the keywords:
Any number of digits: [0-9]+
Any of your keywords: (something|somethingelse|other)
You can use capture-groups as well to have match() return them separately:
var keyword = ["Edit Req'd", "Errors", "Pndg App"];
var regexmatch = RegExp('(\b' + keyword.join('|') + ')([0-9]+)', 'g')
(note that we use the word-boundary \b to make sure keyword is not part of a longer word, and the 'g' flag for global to signal we want multiple results)
Now, match() will only match one result, and we want matches for every keyword, so we’ll use exec() instead:
var txt = "Edit Req'd2<br>Errors5<br>Pndg App11<br>";
var keyword = ["Edit Req'd", "Errors", "Pndg App"];
var regex = RegExp('(\b' + keyword.join('|') + ')([0-9]+)', 'g')
var match = regex.exec( txt ); // ...find the first match
var numbers = [];
while ( match !== null ) {
numbers.push( match[ 2 ]); // #0 of exec() its return-value is the result as a whole: "Edit Req'd2"
// #1 is the value of the first capture-group: "Edit Req'd"
// #2 is the value of the second capture-group: "2"
match = regex.exec( txt ); // ...find the next match
}
console.log("the numbers are:", numbers);
Lastly, do note that regular expressions may look cool, they are not always the fastest (performance-wise). If performance matters a lot, you could use (for example) indexOf() instead.
From your question it seems like you could brush up on your knowledge of regular expressions a little bit. There’s a ton of articles around (just search for “regular expressions basics” or “regex 101”) – like this one:
https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285*

Showing two .substring in the same alert()

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

String.slice and string.substring

I am brand new at programming, especially JS. I seem to be stuck on a split string.
I need to split a string into two separate strings. I know I can do so with the slice and substr like below, which is my sample I have of what I know. I am assuming my name is Paul Johnson. with below I know that if I have an output of first and last name with the parameters I setup, I will have Paul as my first name and Johnson as my second.
var str = document.getElementById("fullName").value;
var firstname = str.slice(0, 4);
var lastname = str.substr(4, 13);
My question is that I am getting hung up on how to find the space and splitting it from there in order to have a clean cut and the same for the end.
Are there any good resources that clearly define how I can do that?
Thanks!
What you're after is String split. It will let you split on spaces.
http://www.w3schools.com/jsref/jsref_split.asp
var str = "John Smith";
var res = str.split(" ");
Will return an Array with ['John','Smith']
str.indexOf(' ') will return the first space
There is a string split() method in Javascript, and you can split on the space in any two-word name like so:
var splitName = str.split(" ");
var firstName = splitName[0];
var lastName = splitName[1];
http://www.w3schools.com/jsref/jsref_split.asp
A good way to parse strings that are space separated is as follows:
pieces = string.split(' ')
Pieces will then contain an array of all the different strings. Check out the following example:
string_to_parse = 'this,is,a,comma,separated,list';
strings = string_to_parse.split(',');
alert(strings[3]); // makes an alert box containing the string "comma"
Use str.split().
The syntax of split is: string.split(separator,limit)
split() returns a list of strings.
The split() function defaults to splitting by whitespace with to limit.
Example:
var str = "Your Name";
var pieces = str.split();
var firstName = pieces[0];
var lastName = pieces[1];
pieces will be equal to ['Your', 'Name'].
firstName will be equal to 'Your'.
lastName will be equal to 'Name'.
I figured it out:
var str = document.getElementById("fullName").value;
var space = str.indexOf(" ");
var firstname = str.slice(0, space);
var lastname = str.substr(space);
Thank you all!

Split string into two parts [duplicate]

This question already has answers here:
Split string once in javascript?
(17 answers)
Closed 8 years ago.
I know there are several ways to split an array in jQuery but I have a special case:
If I have for example this two strings:
"G09.4 What"
"A04.3 A new Code"
When I split the first by ' ' I can simply choose the code in front with [0] what would be G09.4. And when I call [1] I get the text: What
But when I do the same with the second string I get for [1] A but I want to retrieve A new Code.
So how can I retrieve for each string the code and the separate text?
Use
var someString = "A04.3 A new Code";
var index = someString.indexOf(" "); // Gets the first index where a space occours
var id = someString.substr(0, index); // Gets the first part
var text = someString.substr(index + 1); // Gets the text part
You can split the string and shift off the first entry in the returned array. Then join the leftovers e.g.
var chunks = "A04.3 A new Code".split(/\s+/);
var arr = [chunks.shift(), chunks.join(' ')];
// arr[0] = "A04.3"
// arr[1] = "A new Code"
Instead of splitting the string on the space, use a combination of indexOf and slice:
var s = "A04.3 A new Code";
var i = s.indexOf(' ');
var partOne = s.slice(0, i).trim();
var partTwo = s.slice(i + 1, s.length).trim();
You can use match() and capture what you need via a regular expression:
"G09.4 What".match(/^(\S+)\s+(.+)/)
// => ["G09.4 What", "G09.4", "What"]
"A04.3 A new Code".match(/^(\S+)\s+(.+)/)
// => ["A04.3 A new Code", "A04.3", "A new Code"]
As you can see the two items you want are in [1] and [2] of the returned arrays.
What about this one:
function split2(str, delim) {
var parts=str.split(delim);
return [parts[0], parts.splice(1,parts.length).join(delim)];
}
FIDDLE
Or for more performance, try this:
function split2s(str, delim) {
var p=str.indexOf(delim);
if (p !== -1) {
return [str.substring(0,p), str.substring(p+1)];
} else {
return [str];
}
}
You can get the code and then remove it from the original string leaving you with both the code and the string without the code.
var originalString = "A04.3 A new Code",
stringArray = originalString.split(' '),
code,
newString;
code = stringArray[0];
newString = originalString.replace(code, '');

Javascript Split String on First Space

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"

Categories

Resources