Concatenate different variable if exist in JS - javascript

I want to concatenate different variable if exist and return the result.
But I need to separate the value by "-" and return only the variable with value.
So I have this:
var test = "";
var test1 = "";
var test2 = "";
var test3 = "";
var checkTrue = "Rightt";
var checkFalse = "Wrong";
var checkWord = "Helloo";
var checkWord2 = "Bye";
if(checkTrue === "Right"){
test = "This is right"
} else {
test = "";
}
if(checkFalse === "Wrong"){
test1 = "This is wrong"
} else {
test1 = "";
}
if(checkWord === "Hello"){
test2 = "The word is hello"
} else {
test2 = "";
}
if(checkWord2 === "Bye"){
test3 = "The word is hello"
} else {
test3 = "";
}
var result = test + " - " + test1 + " - " + test2 + " -" + test3;
console.log(result);
So I think I need to verify before my var result, if the different variable exists ?
Thank for your help
Actual result:
- This is wrong - -The word is hello
Expected result :
This is wrong - The word is hello

With anything where you want a separator between string values, I find it easier to use Array.prototype.join() which will only place the separator between actual values.
It then becomes easier as you have a single results array that can be joined, only adding values you want rather than testing each of those variables you no longer need.
By pushing on to an array you can also get rid of all those test variables too.
const results = [];
const checkTrue = "Rightt";
const checkFalse = "Wrong";
const checkWord = "Helloo";
const checkWord2 = "Bye";
if (checkTrue === "Right")
results.push("This is right")
if (checkFalse === "Wrong")
results.push("This is wrong")
if (checkWord === "Hello")
results.push("The word is hello")
if (checkWord2 === "Bye")
results.push("The word is hello")
const result = results.join(" - ");
console.log(result);

const test = '';
const test1 = 'This is wrong';
const test2 = '';
const test3 = 'The word is hello'
const result = [test, test1, test2, test3].filter(value => value).join(' - ');
console.log(result);

Related

Pull number value from string

So I need to pull a number value from a string. I currently have a working solution but I feel that maybe I can improve this using a regular expression or something.
Here is my working solution
var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}
As you can see I'm trying to pull the number value from after the "[REF: " string.
// Change of the text for better test results
var subject = "hjavsdghvwh jgya 16162vjgahg451514vjgejd5555v fhgv f 262641hvgf 665115bs cj15551whfhwj511";
var regex = /\d+/g;
let number = subject.match( regex )
console.log(number)
It Will return array for now, and if no match found, it will return null.
For most of the time, when i used this regex i get perfect result unless if string contains decimal values.
var str = 'This is a test message [REF: 2323232]'
var res = str.match(/\[REF:\s?(\d+)\]/, str)
console.log(res[1])
If you don't want to use a regular expression (I tend to stay away from them, even though I know they are powerful), here is another way to do it:
// Your code:
/*var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}*/
// New code:
const subject = "This is a test message [REF: 2323232]";
const codeAsString = subject.split('[REF: ')[1]
.split(']')
.join('');
if (!isNaN(parseInt(codeAsString))) {
console.log('Valid ticket number: ', parseInt(codeAsString));
}
else {
console.log('Invalid ticket number: ', codeAsString);
}
This will extract number
var subject = "This is a test message [REF: 2323232]";
var onlyNum = subject.replace(/.*(:\s)(\d*)\]$/,'$2');
console.log(onlyNum)
Here, same but the number is now a real int
var subject = "This is a test message [REF: 2323232]";
var onlyNum = parseInt(subject.replace(/.*(:\s)(\d*)\]$/,'$2'));
console.log(onlyNum)

What is the best way to target an array or a string with user input, and log its respective index?

What is the best way to target an array or a string, so that when a user types a letter it finds a match and logs the letter and its index in the array (or the string)?For example (set-up):
GUESS THIS MOVIE:
how to train your dragon
___ __ _____ ____ ______
Type a letter to guess, you have 10 TRIES:
User Typed: o
Result: _o_ _o _____ _o__ ____o_
HERES MY CODE:
var fs = require('fs');
var inquirer = require('inquirer');
var displayProgress = require('./checkGuess');
// var checkGuess = require('./checkGuess');
var PlayFunc = function() {
var blanksArr = [];
var currentWord = [];
this.getData = function() {
var stackOv = "";
fs.readFile("words.txt", "utf8", function(error, data){
if (error) throw error;
dataType = data.toLowerCase();
//data in array
var wordArr = dataType.split(',');
//select random from word from data
var compWord = wordArr[Math.floor(Math.random() * wordArr.length)];//random
//split chosen word
currentWord = compWord.split('');
console.log("========================\n\n\n");
//Looping through the word
for (var i = 0; i <= currentWord.length - 1; i++) {
// pushing blanks
var gArr = blanksArr.push("_");
//HYPHENS, COLONS, SPACES SHOULD BE PASSED
stackOv = currentWord.join("").replace(/[^- :'.]/g, "_");
wordString = currentWord.join("");
}
console.log("GUESS THIS MOVIE: ");
fs.writeFile("blanks.txt", stackOv, (err) => {
if (err) throw err;
console.log(wordString);
fs.readFile('blanks.txt', "utf8",(err, word) => {
if (err) throw err;
// console.log("GUESS THIS MOVIE: " + compWord);
blanksTxt = word.split(''); //console.log(string.join('').replace(/[^-: '.]/g, "_"));
displayProgress = new displayProgress();
displayProgress.checkGuess();
});
});
});
}
}
module.exports = PlayFunc;
ON THE NEXT FILE CALLED checkGuess.js I Plan to do the checking (which goes back to my original question (OP).
var fs = require('fs');
var inquirer = require('inquirer');
var PlayFunc = require('./PlayFunc');
var displayProgress = function (){
// console.log("WORKING CONNECTED CHECKGUESS MODULE");
// PlayFunc = new PlayFunc();
// PlayFunc.getData();
var a = blanksTxt.join(''); console.log(a); //string a
var manipulateThisArray = blanksTxt;//reading from blanks.txt
// console.log(manipulateThisArray);
this.checkGuess = function(){
inquirer.prompt([
{
type: "input",
name: "letter",
message: "Type a letter to guess, you have 10 TRIES:"
}
]).then(function(userInput) {
var correctArray = [];
// console.log(userInput.letter);
letterTyped = userInput.letter;
//logic
//test if we can parse through the array
for (var i = 0; i <= manipulateThisArray.length - 1; i++) {
x = manipulateThisArray[i]; console.log(x);
// if userinput letter-value matches chosen words letter value
// replace this chosen worsa letter with userinput value
// if(letterTyped == x.charAt(i)) {
console.log("THERES A MATCH " + x.charAt(i));
// }else {
// console.log("NO MATCH");
// }
}
});
}
}
// checkGuess();
module.exports = displayProgress;
//declaration of the variables we need
//the original string:
const string = "how to train your dragon";
//a string of characters we want to show
const show = "o";
//A resulting string we can work with
var result = "";
//Now we go over every character of our string and
for(const character of string){
//check if the character is inside the characters we want to show
if(show.includes(character)){
//if so we show it by adding it to the result
result += character;
}else{
//If not we add an _ instead
result += "_";
}
}
//At the end we can show the result
alert(result);
For this i would use the 'foo'.replace('bar', 'bar') and make sure that the String contains the input 'foo'.includes('input') also you could use a RegExp.
To get the index you could do a loop through the length of the String and use the 'foo'.indexOf('input', number) that will return -1 if no coincidence

Determine all attributes of a Javascript variable accessed inside a function WITHOUT running it

Is there a clever way to figure out all attributes of an object referenced within a function WITHOUT executing it?
For example let's say I have the following function:
var fun = function(a){
a.text = "hello world";
a.title = "greetings";
a.ran = "fun";
}
I would like some magical function that does:
var results = magical_function(fun, {});
// results = ["text", "title", "ran"];
Basically it's returning all attributes of the argument object that will be accessed inside the fun function, WITHOUT having to actually execute fun.
I said "without running" it because I don't want the act of checking this affect any outside app logic, but I am fine as long as the checking doesn't influence the outside world.
function.toString() is going to return a parsable string. Use Regex on that.
var fun = function(a){
a.text = "hello world";
a.title = "greetings";
a.ran = "fun";
}
var fun2 = function(x){
x.text = "hello world";
x.title = "greetings";
a.ran = "fun";
}
function magical_function(func) {
var data = func.toString();
var r = /a\.([a-z]+)/g;
var matches = [];
var match;
while ((match = r.exec(data)) != null) {
matches.push(match[1]);
}
return matches;
}
function magical_function_2(func) {
var data = func.toString();
var attribute_finder_r = new RegExp('function \\(([a-z]+)\\)');
var attribute_name_match = attribute_finder_r.exec(data);
if (!attribute_name_match) {
throw 'Could not match attribute name';
}
var attribute_name = attribute_name_match[1];
var r = new RegExp(attribute_name + '.([a-z]+)', 'g');
var matches = [];
var match;
while ((match = r.exec(data)) != null) {
matches.push(match[1]);
}
return matches;
}
console.log(magical_function(fun));
console.log(magical_function_2(fun2));
var myObj = {
text: '',
title: '',
ran: ''
}
var fun = function(a){
a.text = "hello world";
a.title = "greetings";
a.ran = "fun";
}
function magical_function(func, obj) {
var data = func.toString();
var keys = Object.keys(obj);
var regExp = '';
for (let i= 0; i < keys.length; i++) {
if (keys.length > 1 && ((i+1) < keys.length)) {
regExp += keys[i] + '|';
}
else if (keys.length == 1 || ((i+1) == keys.length)) {
regExp += keys[i];
}
}
regExp = '\.(['+ regExp +']+)\\s*=';
var r = new RegExp(regExp, 'g');
var matches = [];
var match;
while ((match = r.exec(data)) != null) {
if (Object.keys(obj).includes(match[1]))
matches.push(match[1]);
}
return matches;
}
console.log(magical_function(fun, myObj));
There's no way those attributes are going to get set before running the function.
The only thing you can do is to write another version of the function which only accesses the object passed and returns the result.

How to find a word in a string?

The challenge is to "find Waldo." I'm trying to figure out how to find a word in a function/string." Return the index of where in the string 'Waldo' starts."
function findWaldo(str) {
var waldoPosition;
return waldoPosition
}
Simple task to do:
function findWaldo(str) {
return str.indexOf("waldo"); //the string you are looking for
}
It is explained quite well here.
There should be a library that does it easily, like string.indexOf, but you can do it manually with this algorithm:
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";
for (int x = 0; x < yourText.Lenght; x++)
{
if(yourText[x] == toSearch[0])
if((count + 1) == toSearch.Lenght)
return x;
else
count = 0;
//here we'd say ehh there's not Waldo on the string
}
To find a word or letter you can use x.indexOf method, hope to below code helps.
// Question
const findWord = (str, findWord) =>{
let total = ""
let error = false
let errorMessage = "";
if(str != null && str != ""){
error = false
if(!str.indexOf(findWord)){
total = `there is no ${findWord} in str peremeter.
`
}else{
total = `the position of ${findWord} is ${str.indexOf(findWord)}`
}
}else{
error = true;
errorMessage = "Please fill the str perimeter."
return errorMessage
}
return total
}
// Calling Function
console.log(findWord("Hello World", "World"))

How to connect javascript var with text?

How to connect javascript var xx with /\ and \b/ ?
https://jsfiddle.net/6r4o5278/6/
<div onclick="check()">CLICK HERE</div>
<script>
function check() {
var str = "abcdefg";
var xx = "abc";
if (/\+xx+\b/.test(str))
{
alert("found");
} else
{
alert("not found");
}
}
</script>
What do you mean by 'connect javascript var xx with /\ and \b/'. Furthermore see:
http://www.w3schools.com/jsref/jsref_regexp_test.asp
// The string:
var str = "Hello world!";
// Look for "Hello"
var patt = /Hello/g;
var result = patt.test(str);
// Look for "W3Schools"
patt2 = /W3Schools/g;
result2 = patt2.test(str);
Declare your regex before testing.
....
var xx = /abc\b/;
if (xx.test(str)) {
...
Note that this will not match the string "abcdefg" because \b is a Word Boundary flag.
use this one surely work...:)
var test = '/\\' + xx + '\\b/';
console.log(test);
it will be /\abc\b/.
Try to construct the expression this way:
<script>
function check(value) {
var str = "abcdefg";
var re = new RegExp(value);
var found = str.match(re);
if (found) {
console.log(value + " - found");
}
else
{
console.log(value + " - not found");
}
}
check('xsxsd');
check('abc');
check('refer');
check('cde');
</script>

Categories