How to split a name string with multiple spaces? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i want to sort firstname and lastname, my problem is when the user has multiple first name, e.g.:
'Michael Jordan Atticus Smith'
basically, the Smith is the last name there, how do i split firstname and lastname with it? the result i want from is:
'Michael Jordan Atticus' 'Smith'

let str = 'Michael Jordan Atticus Smith';
console.log( ex1(str) );
console.log( ex2(str) );
console.log( ex3(str) );
function ex1(str) {
let names = str.match(/(.*?)\s(\S+)$/); // (1)
return [ names[1], names[2] ];
}
function ex2(str) {
let names = str.split(" ");
return [names.pop(), names.join(" ")].reverse(); // (2)
}
function ex3(str) {
let last = ""
str = str.replace(/\s(\S+)$/, function(full_match, parenthesis_1) {
last = parenthesis_1;
return "";
});
return [str, last];
}
(1) match() returns an array of matched strings. Also, see the RegEx cheet sheet
(2) Array pop() method removes, and returns the last element. Code executes from the left to right, so, the second names.join(" ") collects together 3 names left.

Related

How to find characters that are there in one string and not there in another in javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
I want to find distinct characters that are there in one string and not in another. Suppose firstString contains ABC and secondString contains BC now output op1 should contain 'characters that are distinctly there in the firstString but not in the secondString' i.e. A and op2 should contain 'characters that are distinctly there in the secondString but not in the firstString' i.e. in this case null. If firstString is 'SBG' and secondString is 'BANGALORE' op1 should be 'S' op2 should be 'ANLORE'
I would recommend using Javascripts Set and filtering out elements which are not present:
// returns the distinct characters found in string1
// but not in string2 as an array
function findDistinctChars(string1, string2) {
const set1 = new Set(string1)
const set2 = new Set(string2)
return [...set1].filter(char => !set2.has(char))
}
// example usage
const s1 = "aaabcde"
const s2 = "efghi"
// run for string one and then two
const op1 = findDistinctChars(s1, s2)
const op2 = findDistinctChars(s2, s1)
// output results
console.log(op1)
console.log(op2)

If I have a list of split arguments seperated by spaces, how would I join the ones within qoutes back together? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
My argument parser works by taking every word in your string and splitting it by the spaces. I want to put the arguments back together, but only if it is between "'s, like this
My argument list would look like this:
['"Hello', 'there,', 'my', 'friend!"', '"1', '2', '3"', 'gold']
And I want to put them back together:
['"Hello there, my friend!"', '"1 2 3"', 'gold']
But I can have multiple strings, and store each one of these full strings in an array, let's call it fullStrings.
I also want to make it so one-worded, no-quote arguments will also be included.
Kind of simple solution in declarative way
Using: Array#join String#replaceAll String#split
const result = ['"Hello', 'there', ',', 'my', 'friend!"', '"1', '2', '3"']
.join(' ') // '"Hello there , my friend!" "1 2 3"'
.replaceAll(' ,', ',') // '"Hello there, my friend!" "1 2 3"'
.replaceAll('" "', '"" ""') // '"Hello there, my friend!"" ""1 2 3"'
.split('" "'); //['"Hello there, my friend!"', '"1 2 3"']
result.map((o) => console.log(o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
After many, many hours of head scratching I came up with this abombination of a regex:
function parseArgs(input) {
return Array.from(input.matchAll(/"((?:[^"]|"\S*")*)"(?=\s)|(?<=^|\s)([^"\s]+)(?=$|\s)/g)).map(a => a[2] ?? a[1]);
}
console.log(parseArgs(`"Hello there, my friend!" "1 2 3" gold`))
You could try something like this but it does include a space after the there i.e. there , which may not be suitable for you?
output = ['"Hello there , my friend!"', '"1 2 3"']
const words = ['"Hello', 'there', ',', 'my', 'friend!"', '"1', '2', '3"']
let fullString = '';
words.forEach((word, index) => {
fullString += (index > 0)? ` ${word}`:`${word}`; //create sentence
});
// split on '"' and filter out empty values
const fullStrings = fullString.split('"').filter(Boolean).map((r)=>{
let result = (r != ' ')? `"${r}"`: null;
return result;
}).filter(Boolean); //remove null
console.log(fullStrings);

String with character repetition [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Can someone help me on this one? Given a string, I have to return a string in which each character (case-sensitive) is repeated once.
doubleChar("String") ==> "SSttrriinngg"
doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
doubleChar("1234!_ ") ==> "11223344!!__ "
function doubleChar(str) {
}
You can use repeat() method for this like:
function doubleChar(str) {
return [...str].map(s => s.repeat(2)).join('')
}
console.log(doubleChar("String"))
console.log(doubleChar("Hello World"))
console.log(doubleChar("1234!_ "))
Try this:
const str = 'hello'
let arr = str.split('')
const double = arr.map(i => i += i).join('')
console.log(double)

Using Dynamic data in a Regular Expression [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a list that looks something like this :
listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"]
The web page shows a textArea, where the user can add data like :-
Hello, My fav subject is <<English>>
or
I like <<Biology>> , its the best
I want to show a validation error if the user enters anything else from what in the listA between the <<>>, the rest of message can be anything.
I tried using regular expression but I cant figure it out and I couldn't figure out directives. Please ask if more clarification is required
this is what I have tried so far :
checkText(event) {
// const regex = /(?:^|\s)<<(.*?)>>(?:\s|$)/g;
var str = this.editClauseObj.textObj.text;
console.log("str",str);
let name_val = 'Name';
const regex = /^([a-zA-Z]*\s)*[<<name_val>>]*\s*[a-zA-Z\s]*$/g
if (!regex.test(str)) {
this.showError = true;
this.errorMessage = "Please enter a valid value inside <<>>"
console.log("test", this.showError);
} else {
// do something else
this.showError = false;
}
}
const listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"];
const text = "Hello, My fav subject is <<English>> \n I like <<Biology>> , its the best \n I like <<Hello>> , its the best ";
// Look for << char and then ([^>>]+) except this >> char for 1 and more time and find the next >> char.
const r = /<<([^>>]+)>>/g
let found=[];
while( current_found = r.exec( text ) ) {
found.push( current_found[1] );
}
// all found items in the text
console.log(found);
// filter which is not matching
var final = found.filter(function(item) {
return !listA.includes(item);
});
console.log(final);

JavaScript prototypes - technical interview [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I had a JavaScript interview last wednesday, and I had trouble with one of the questions. Maybe you guys can give me hand with it?
The question was: how would you go about this printing var a and s to the console, in camel case, with the help of a prototype function...
var s = “hello javier”;
var a = “something else”;
String.prototype.toCamelCase = function() {
/* code */
return capitalize(this);
};
...so the result is the same as doing this?
console.log(s.toCamelCase());
console.log(a.toCamelCase());
>HelloJavier
>SomethingElse
Thanks!
var s = 'hello javier';
var a = 'something else';
String.prototype.toCamelCase = function() {
return capitalize(this);
};
function capitalize(string) {
return string.split(' ').map(function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}).join('');
}
console.log(a.toCamelCase());
console.log(s.toCamelCase());
Reference
How do I make the first letter of a string uppercase in JavaScript?
I would go with something like this:
var s = "hello javier";
var a = "something else";
String.prototype.toCamelCase = function() {
function capitalize(str){
var strSplit = str.split(' ');
// starting the loop at 1 because we don't want
// to capitalize the first letter
for (var i = 1; i < strSplit.length; i+=1){
var item = strSplit[i];
// we take the substring beginning at character 0 (the first one)
// and having a length of one (so JUST the first one)
// and we set that to uppercase.
// Then we concatenate (add on) the substring beginning at
// character 1 (the second character). We don't give it a length
// so we get the rest.
var capitalized = item.substr(0,1).toUpperCase() + item.substr(1);
// then we set the value back into the array.
strSplit[i] = capitalized;
}
return strSplit.join('');
}
return capitalize(this);
};
// added for testing output
console.log(s.toCamelCase());
console.log(a.toCamelCase());

Categories

Resources