JavaScript prototypes - technical interview [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 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());

Related

Need to have one string from Looped Chars JS [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
need to get the output as 1 string instead of looped string
the output I got each letter on its own
need to have the second output which is one word
Thanks in advance:D
let start = 0;
let swappedName = "elZerO";
for (let i = start; i<swappedName.length; i++){
if (swappedName[i] == swappedName[i].toUpperCase()) {
console.log(swappedName[i].toLowerCase());
}else {
console.log(swappedName[i].toUpperCase());
}
}
//Output
E
L
z
E
R
o
// Need to be
"ELzERo"
Use string = string0+string1 , or keep adding values to an array, then join the array with array.join()
MasteringJs has a great guide on ways to merge characters and strings.
let start = 0;
let swappedName = "elZerO";
var outputString="";
var outputStringArray=[];
var newChar="";
for (let i = start; i<swappedName.length; i++){
if (swappedName[i] == swappedName[i].toUpperCase()) {
newChar = swappedName[i].toLowerCase();
}else {
newChar=swappedName[i].toUpperCase();
}
outputStringArray.push(newChar);
outputString+=newChar;
}
console.log("[Output using string1 + string 2] is "+outputString); // Another example of concating string
console.log("[Output using array.join] is "+outputStringArray.join("")); // Another example of concating string
// Need to be
"ELzERo"

How to count character followed by Special Character in string using 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 3 years ago.
Improve this question
My string is: Hello 1⃣2⃣3⃣ world.
The expected result is 3 (1⃣ 2⃣ and 3⃣)
Matching condition has total 12 value below:
(0⃣ 1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣ 7⃣ 8⃣ 9⃣ *⃣ #⃣ )
How to use javascript to count total of result? Thank you.
// Get code of emoji
function getEmojiUnicode(emoji) {
var comp;
if (emoji.length === 1) {
comp = emoji.charCodeAt(0);
}
comp = (
(emoji.charCodeAt(0) - 0xD800) * 0x400
+ (emoji.charCodeAt(1) - 0xDC00) + 0x10000
);
if (comp < 0) {
comp = emoji.charCodeAt(0);
}
return comp.toString("16");
};
// count how many times emoji appears
function countSpecialCharacter(string) {
// what should I write here?
return result;
}
var inputString = 'Hello 1⃣2⃣3⃣ world';
var output = countSpecialCharacter(inputString); // this should be 3
Definition of Combining Enclosing Keycap is here
https://emojipedia.org/combining-enclosing-keycap/
1) Split the string by ' ' and get the words
2) Check each word if it had enclosing keyCap
3) If so, return length/2 (because each char has one enclose)
const count = line => {
const valid_chars = Array.from("0123456789*#");
const sp_chars = line.split(" ").find(x => x.includes("⃣"));
if (sp_chars && sp_chars.length % 2 === 0) {
return Array.from(sp_chars).filter(x => valid_chars.includes(x)).length;
}
return 0;
};
console.log(count("Hello 1⃣2⃣3⃣-⃣ world"));
I think what you need to do is iterate through each character you have in your string, looking at the unicode character. Once you have this you can compare this to a list of unicode characters you know are 'Keycaps' - giving you the count.
I.e (this is just checking the first character in a string as an example):
function isCharacterAKeycap(str) {
var keycapUnicodeValues = [8000, 8001, 8002];
return keycapUnicodeValues.includes(str.charCodeAt[0]);
}
str = "1⃣";
isCharacterAKeycap(str);

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

search() javascript doesn't work if first character there isn't in the string [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 6 years ago.
Improve this question
Hello I know that search() in javascript doesn't work (returns -1) if first charachter does not exist in the string...
$('#search-vulc').on('keyup', function() {
var textinsert = ($(this).val()).toLowerCase();
var nome_search = "home";
if (nome_search.search(textinsert) != -1) {
alert('ok');
}
else {
alert('not');
}
});
And so in this example if we write "x home", returns -1.
But is there a way to "solve" this problem ?
in short, if i write "x home" anyway there is the word home...
I would like a method that in this case doesn't return -1
You're searching for "x home" in "home".
Thus it is returning -1.
if (nome_search.search(textinsert) != -1)
Should be
if (textinsert.search(nome_search) != -1)
Is this nome_search.search(textinsert) simply backwards? textinsert.search(nome_search)
Refactored code:
function getStringPostion(re, str) {
var midstring;
var position = str.search(re);
midstring=(position != -1) ? ' contains ':' does not contain ';
console.log(str + midstring + re);
console.log(position );
return position;
}
var foundAtPosition = getStringPostion("home","x home");
Iterating trough all the inserted strings might do:
var f = function(re) {
var textinsert = ($(this).val()).toLowerCase().split(" ");
var nome_search = "home";
var result = 0;
for (var i = 0; i<textinsert.length; i++){
console.log(textinsert[i]);
if (nome_search.search(textinsert[i]) != -1) result++;
}
return result > 0 ? alert('ok') : alert('not') ;
};
as long as they are separated by spaces like in your example.

Generate JS Regex from a set of strings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there any way or any library out there that can compute a JS RegEx from a set of strings that I want to be matched?
For example, I have this set of strings:
abc123
abc212
And generate abc\d\d\d ?
Or this set:
aba111
abb111
abc
And generate ab. ?
Note that I don't need a very precise RegEx, I just want one that can do strings, . and .*
Not without producing all the possible outcomes of a certain Grammar, some of which are infinite. This means it's not possible in the general case for finding a specific wanted grammar from a given input set. Even in your cases, you need to give every possible production of the Grammar (regular expression) in order to know exactly what regular expression you are happening to look for. For example the first set, there are several regular expressions that can match it, some of which could be:
abc[0-9][0-9][0-9]
abc[1-2][0-5][2-3]
abc[1-2][0-5][2-3]a*
abc\d*
abc\d+
abc\d+a*b*c*
...
And so on. That being said you could find a grammar that happens to match that sets conditions. One way is to simply brute-force the similarities and differences of each input item. So to do this with the second example:
aba111
abb111
abc
The ab part is the same for all of them so we start with ab as the regexp. Then the next character can be a, b or c so we can say (a|b|c). Then 1 or empty three times. That would result in:
ab(a|b|c)(1|)(1|)(1|)
Which is a correct regular expression, but maybe not the one you wanted.
May be this is too simple but you can use this,
var arr = ['abc121','abc212','cem23'];
var regex_arr = [];
arr.sort(function(a, b){return -a.length+b.length;});
for(var i in arr[0]){
for(var j in arr){
if(i>=arr[j].length){
regex_arr[i] = {value:'',reg:'*',use_self:false};
}else{
var c = arr[j][i];
var current_r = '.';
if(isNaN(c)){
if(/^[A-Za-z]$/.test(c)){
current_r = '\\w';
}else{
current_r = '\\W';
}
//... may be more control
}else{
current_r = '\\d';
}
if(!regex_arr[i]){
regex_arr[i] = {value:c,reg:current_r,use_self:true};
}else{
if(regex_arr[i].value!=c){
if(regex_arr[i].reg!=current_r){
regex_arr[i].reg = '.';
}
regex_arr[i].use_self = false;
regex_arr[i].value = c;
}
}
}
}
}
var result = '';
for(var i in regex_arr){
if(regex_arr[i].use_self){
result += regex_arr[i].value;
}else{
result += regex_arr[i].reg;
}
if(regex_arr[i].reg=='*'){
break;
}
}
console.log("regex = "+result);
for(var i in arr){
var r = new RegExp(result);
console.log(arr[i] + ' = '+r.test(arr[i]));
}
Results
regex = \w\w\w\d\d*
abc121 = true
abc212 = true
cem23 = true

Categories

Resources