Function that adds equal amount of whitespace to both ends of string - javascript

function space(str,numSpace){
str = "";
numSpace = (" " + " ");
document.write(numSpace + str + numSpace);
}
console.log(space("hi", " "));
This is not working out, I'm not too sure how I can add whitespace to both ends of a string.

This is not working out, i'm not too sure how I can add whitespace to
both ends of a string.
you're always resetting the parameter str to empty string hence the unexpected behaviour.
there are two ways you could solve the issue at hand.
1) you could use console.log() inside the method, example:
function space(str, numSpace) {
var result = numSpace + str + numSpace;
console.log(result);
}
space("hi", " ");
2) you could return the value then use console.log():
function space(str, numSpace) {
return numSpace + str + numSpace;
}
var result = space("hi", " ");
console.log(result);

Don't overwrite you're function's parameters with constants, and don't use document.write but return the result:
function space(str, numSpace) {
return numSpace + str + numSpace;
}
console.log(space("hi", " "));
Also I would suggest renaming numSpace to spaces, as the former suggests to be used with an integer count, not a string of spaces.

Related

Reading values with different datatypes inside a string in javascript

Assume i have a string
var str = " 1, 'hello' "
I'm trying to give a function the above values found in str but as integer and string- not as one string-
for example myFunc(1,'hello')
how can i achieve that
i tried using eval(str),
but I'm getting invalid token ,
How can i solve this?
The following should work with any number of arguments.
function foo(num, str) {
console.log(num, str);
}
const input = "1, 'hel,lo'";
const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');
foo(...args);
You've almost got the right idea with eval(str) however, that isn't the thing you actually want to evaluate. If you do use eval(str), it is the same as saying eval(" 1, 'hello' ")
However, what you really want to do is:
eval("func(1, 'hello world')).
To do this you can do:
eval(func.name + '(' + str.trim() + ')');
Here we have:
func.name: The name of the function to call. You can of course hard code this. (ie just write "func(" + ...)
str.trim(): The arguments you want to pass into the given function. Here I also used .trim() to remove any additional whitespace around the string.
Take a look at the snippet below. Here I have basically written out the above line of code, however, I have used some intermediate variables to help spell out how exactly this works:
function func(myNum, myStr) {
console.log(myNum*2, myStr);
}
let str = " 1, 'hello, world'";
// Build the components for the eval:
let fncName = func.name;
let args = str.trim();
let fncStr = fncName + '(' + args + ')';
eval(fncStr);
Alternatively, if you only wish to pass in two arguments you can use .split(',') on your string to split the string based on the comma character ,.
Using split on " 1, 'hello' " will give you an array such as this one a:
let a = [" 1", "'hello'"];
Then cast your string to an integer and remove the additional quotes around your string by using .replace(/'/g, ''); (replace all ' quotes with nothing ''):
let numb = +a[0].trim(); // Get the number (convert it to integer using +)
let str = a[1].trim().replace(/'/g, ''); // get the string remove whitespace and ' around it using trim() and replace()
Now you can call your function using these two variables:
func(numb, str);
function func(myNum, myStr) {
console.log('The number times 2 is:', myNum*2, "My string is:", myStr);
}
let arguments = " 1, 'hello' ";
let arr = arguments.split(',');
let numb = +arr[0].trim(); // Argument 1
let str = arr[1].trim().replace(/'/g, ''); // Argument 2
func(numb, str);

regex replace jumbles string

This is my console.log:
str : +0-D : replace : Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
I have the following function:
function replaceAll_withMatching(str, find, rep, prodId) {
//console.log(str + " : " + find + " : " + rep + " : " + prodId);
var returnString = "";
if (find.toLowerCase() == str.toLowerCase()) {
returnString = rep;
} else {
escfind = "\\" + find ;
var regexp = new RegExp(escfind, "i");
var match = regexp.test(str);
if (match) {
var regAHREF = new RegExp("\\<a", "i");
var AHREFMatch = regAHREF.test(str);
if (AHREFMatch == false) {
str = str.replace(regexp, rep);
str = replaceProductAll(str, PRODUCT_PLACEHOLD, prodId);
} else {
var aTagText = $($.parseHTML(str)).filter('a').text();
if ((find !== aTagText) && (aTagText.indexOf(find) < 0)) {
console.log(regexp);
console.log("str : " + str + " : replace : " + str.replace(regexp, rep));
str = str.replace(regexp, rep);
}
}
}
//console.log(str);
returnString = str;
}
//returnString = replaceProductAll(returnString, PRODUCT_PLACEHOLD, prodId);
return returnString;
}
This function looks for a "<a>" tag, if it doesn't find one then it does the replace. If it does find one it has some conditions that if everything checks out it does another replace.
The string that I'm passing in has been already "parsed" on the +0:
+0-D
In the second pass I'm expecting it to find the "D" in the above string, and then do the following replacement:
D
But as you can see, after the 2nd replace it is jumbling the string and producing malformed HTML
Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
More Context:
I have a string that needs to have a replace done on it. This is existing code so I'm not in a position to rework the function.
The original string is: +0-D
This string gets passed into the function below multiple times looking for matches and then if it finds a match it will replace it with the value (also passed in as a parameter).
When the +0-D gets passed in the first time the +0 is matched and a replace is done: +0
Then the next time the string is passed in: +0-D. The function finds the D as a match and it looks like it attempts to do a replace. But it is on this pass that the string gets jumbled.
Ultimately what I'm expecting is this:
+0-D
This is what I'm currently getting after the 2nd attempt:
Da href="Javascript:PostRating('','|P|622','+0')">+0</a>-D
Further Context:
The +0-D is one of many strings this function handles. Some are very simple (i.e. Just +0), others are much more complex.
Question:
Based on the above, what do I need to do to get the regex to not jumble the string?
The problem was in the escfind:
escfind = "\\" + find;
var regexp = new RegExp(escfind,"i");
var match = regexp.test(str);
The first thing I did was in the 2nd replace clause I created a new RegExp to not use the "\\" + find;
if((find !== aTagText) && (aTagText.indexOf(find) < 0)){
try{
var regexp2 = new RegExp(find,"i");
var match2 = regexp2.test(str);
console.log(str.replace(regexp2,rep));
}catch(err){
console.log(err);
}
}
Then my string began to return as expected, however, when I opened it up to all the variations I was getting the Unexpected quantifier error.
Then I found this question - which lead me to escape out my find:
Once I replaced my code with this:
escfind = find.replace(/([*+.?|\\\[\]{}()])/g, '\\$1');
Then I got the output as expected:
<a href='+0'>+0</a>-<a href='D'>D</a>

How to add spaces in the first and the end of a string variable

I'm trying to add spaces in the first and the end of this string variable, I tried to convert the string to an array, then add space with push() and unshift() ... but it returns "x.push is not a function"
function space_fb(x){
x.split(" ");Array.prototype.slice.call
x.push (" ") ;
x.unShift (" ") ;
return x.join(" ");;
}
var xxx = "Medardo";
space_fb(xxx);
alert(xxx);
There is many ways this can be done you could simply add the spaces in your string value for example like " Medardo " and it will work, But My example would handle dynamic string data.
You dont need that space_fb function at all its dead simple:
var xxx = " " + "Medardo" + " ";
alert(xxx);
Edited as OP wanted it in a function as his "teacher wants him to"
function AddSpaces(x){
return " " + x + " ";
}
var xxx = AddSpaces("Medardo")
alert(xxx);
How about this? JSON.stringify ist just to show the output in this way.
var x = "foo";
function addSpaces(string){
var a = string.split("");
a.push(" ");
a.unshift(" ");
return a.join("");
}
document.write(JSON.stringify(addSpaces(x)));
This is because you are using method split but the variable is not being assign
you have two options
1.- x = x.split();
or
2.- var myArray = x.split(" ");
This is all you will need do not use the + + operators. A . is a concatenation operator.
var xxx = ' '.xxx.' ';
As mentioned by #itsgoingdown, in JavaScript you can append strings using the + operator. There is really no need to split the string into a character array and push/unshift to add spacing.
function space_fb(x){
x.split("");Array.prototype.slice.call
x.push (" ") ;
x.unShift(" ") ;
return x.join("");;
}
var xxx = "Medardo";
space_fb(xxx);
alert(xxx);

Checking whether or not two strings are identical in size and hold identical values

string1 = prompt("String 1?");
string2 = prompt("String 2?");
if (string1.length == string2.length)
alert (string1 + " and " + string2 + " : are identical in size.")
else
alert (string1 + " and " + string2 + " : not identical in size.")
for(i=0; i<string1.length; i++)
{
for(j=0; j<string2.length; j++)
{
if (string1.charAt[i] == string2.charAt[i])
alert (string1.charAt[i] + " and " + string2.charAt[j] + " : are identical values.")
else
alert (string1.charAt[i] + " and " + string2.charAt[j] + " : are non-identical values.")
}
};
The second part of the code keeps returning "undefined" and "undefined". I'm trying to compare both strings to see if they hold identical values. Would appreciate any help!
You are using the wrong index when you compare the characters. This:
if (string1.charAt[i] == string2.charAt[i])
should be:
if (string1.charAt(i) == string2.charAt(j))
Besides using parantheses, as Rob W pointed out, you should use the variable j to access the character in string2.
I'm not sure why you are comparing each character in one string with every character in the other string, though... If you actually want to compare each character to the corresponding character in the other string, then you should not have nested loops but a single loop.
Use charAt(i) instead of charAt[i] (parentheses instead of square braces).charAt is a String method, not a string's property.
Equivalent methods:
string1[i]
string1.charAt(i)
string1.substr(i, 1)
string.substring(i, i+1)
Wtf?
string1 === string2
Why not?

Javascript string formatting, short question

How can I use javascript to add a number (any number between 0-100) followed by a underscore, before the variable value?
Example:
2000 becomes 12_2000 //a number of my choice is added followed by an underscore
hello becomes 12_hello
The number (12 in this case) is a constant chosen by me!
Thanks
i + '_' + x where i is the number and x is an arbitrary value.
Just use string concatenation:
var res = '12_' + myNum;
Or with a variable prefix:
var res = prefix + '_' + myNum;
This is just basic string concatenation, which can be done with the + operator:
var num = 2000;
"12_" + num;
// "12_2000"
var_name = "2000";
output = "12_" + var_name;
function prefixWithNumber(value, number) {
return number + "_" + value;
}
This expression is evaluated as (number + "_") + value. Since one of the operants in the first addition is a string literal, the second argument number is converted (coerced) to a string. The result is a string, which causes the third argument to be converted to a string as well.
This is what the JS engine does behind the scenes:
(number.toString() + "_") + value.toString();
Maybe you're looking for something like this:
Object.prototype.addPrefix = function(pre){
return pre + '_' + this;
};
This allows code like:
var a = 5;
alert(a.addPrefix(7));
or even:
"a string".addPrefix(7);
Joining an array can be faster in some cases and more interesting to program than "+"
[i, '_', myNum].join('')

Categories