JavaScript trim character - javascript

I want to delete "()" from each value. How would I do that?
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
console.log(arr[i]);
}

Since all the other answers are unnecessarily complicated, here's a simple one:
arr = arr.map(s => s.slice(1, -1));
You can do it in-place too if you prefer; the important part is .slice(1, -1), which takes a substring starting from the character at index 1 (the second character) and ending before the last character (-1).
String.prototype.slice documentation on MDN

var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
var arrLength = arr[i].length -2;
var shortArr = arr[i].substr(1,arrLength);
console.log(shortArr);
}
This gets one character less on the front and back

use replace
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++){
var x = arr[i];
x = x.replace(/[()]/g,"");
console.log(x);
}
note:
i dedited, because alexander was right
so u need to use regex, "g" for search globally,
"[" "]" to find all character inside

This is fast and should work no matter how many parenthesis are in the string, it will remove them all.
arr[i] = arr[i].split(/\(|\)/g).join("");

This matches ( followed by anything that isn't ) followed by ). Would also fail for "(test(ing)123)", (if you care)
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
arr[i] = arr[i].replace(/\(([^)]+)\)/g, "$1");
}
This is much more simple/faster (but arguably more brittle):
var arr = ["(one)","(two)","(three)","(four)","(five)"];
for(var i = 0; i < arr.length; i++) {
arr[i] = arr[i].substr(1, arr[i].length - 2);
}

Related

What is the problem in this simple js code?

I am wondering what`s the problem with this simple code. I am making a function where I need to get the length of the shortest word in a string. I know that I can find this function anywhere but,
why mine isn't working?
function findShort(s){
var arr = s.split(" ");
var out = 1000;
for (var i = 0; i < arr.length-1; i++){
if (arr[i] <= out){
out = arr[i].length;
}
}
return out;
}
The above function returns 1000 instead.
You need to compare the length of each word (arr[i].length), not each word itself (arr[i]) to the shortest length so far.
function findShort(s){
var arr = s.split(" ");
var out = 1000;
for (var i = 0; i < arr.length-1; i++){
if (arr[i].length <= out){ // <-- here!
out = arr[i].length;
}
}
return out;
}
Your problem is that when you compare strings in javascript, it doesn't use it's length. You have to use the "length" attribute of a String, like in the fixed code below. Also you have to save the result to give an output
function findShort(s){
var arr = s.split(" ");
var comp = 1000;
var out = "";
for (var i = 0; i < arr.length-1; i++){
if (arr[i].length <= comp){
comp = arr[i].length;
out = arr[i];
}
}
return out;
}
There still is a problem, if you want to have an array returned with all the shortest words (same length). You could add another if statement and make it add the word to an array when it's the same length, and clear it when there was found a shorter one.

Why do I need to declare the length in the forloop and not use it directily?

I have a function to capitalize the first letter of every word in the string that I use as attribute.
But I can't figure it out why I need to declare in the for loop the length of the split and not use it directly.
This is the code that works:
function LetterCapitalize(str) {
wordarr = str.split(" ");
for (var i = 0, n = wordarr.length; i < n; i++) {
wordarr[i] = wordarr[i][0].toUpperCase() + wordarr[i].slice(1);
}
str = wordarr.join(" ");
return str;
}
The problem that I have: I don't understand why this works:
for (var i = 0, n = wordarr.length; i < n; i++) {...
but this doesn't:
for (var i = 0, i < wordarr.length; i++) {...
Thanks for any advice that you guys can give me.
Forloop has three statements. Initialization, condition and incrementing. Each statement is separated by ';'. But in your forloop, initialization and condition parts are separated by ',' instead of ';'. Javascript thinks they both belong in one statement.
Following should work
for (var i = 0; i < wordarr.length; i++) {
According to MDN "for" loop can have three blocks:
for ([initialization]; [condition]; [final-expression])
statement
But in your case you use "," instead of ";".
This one should work perfectly for you
function LetterCapitalize(str) {
wordarr = str.split(" ");
for (var i = 0, n = wordarr.length; i < n; i++) {
wordarr[i] = wordarr[i][0].toUpperCase() + wordarr[i].slice(1);
}
str = wordarr.join(" ");
return str;
}

Buggy Javascript Function Complains Missing For Loop ")"

The following is my simple function to create a range array between two numbers. The problem is that console keeps complaining that for loop has a missing bracket ")" but I can plainly see that it is not missing. Please help!
function range(start, end){
var len = end - start;
for (var i = 0; i <= len; i++){
var arr[i] = x + i;
}
return arr[];
}
console.log(range(1, 10));
console.log(arr.length);
Here is the output:
SyntaxError: missing ) after for-loop control (line 3)
Edit
for (var i = 0; i <= len; i++){
was
for (var i = 0; i <= len; i++;){
remove
↓
for (var i = 0; i <= len; i++;)
Remove the final semicolon:
for (var i = 0; i <= len; i++)
Your code has other issues, but this answers the question asked. I suggest you pull out a guide on JavaScript and correct your syntax throughout your code.
There were three errors. I cannot fix undeclared 'x', which is either in outter scope (global) or this is an error that you have to fix with your own logic.
function range(start, end){
var arr = []; //declare your array
var len = end - start;
for (var i = 0; i <= len; i++){
arr[i] = x + i; //here x is undeclared, single array indices cannot be declared this way
}
return arr;
}
console.log(range(1, 10));
console.log(arr.length);
You shouldn't put a semi-colon (;) after the last statment in the for loop. Remove it.
It's very unlikely that something like a for loop is buggy in JavaScript, in a language that is usef by millions every day.

Doubling each letter in a String in js

I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));

Need to filter out repeating consecutive characters in a string using JavaScript

It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.
For example, if I pass a string "hhhhheeeelllloooooohhheeeyyy", then the function should return an array = ["h","e","l","o","h","e","y"].
This is my code.
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}
for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}
so, if I pass a string, such as "hhhhheeeeeellllloooo",it doesn't work as I intend it to because the value of j keeps incrementing, hence I can't filter out all the identical elements.
I tried tweaking the logic, such that whenever the unique[j] === unique[k] the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.
This got me an infinite loop.
I need your help.
The second for loop is fail because unique.length is not constant during the run.
I think your problem can be solved like this:
var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
if(iterable[i] != temp) {
unique.push(iterable[i]);
temp = iterable[i];
}
}
Hope it helps!
You only need to compare the current index of iterable against the last character in unique:
function(iterable){
var unique = []
for(var i=0; i< iterable.length; i++){
if(unique.length < 1){
unique.push(iterable[i])
} else if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
I think this will help you:
var word="hhhhheeeelllloooooohhheeeyyy"
function doit(iterable){
var unique = []
unique[0]=iterable[0]
for(var i=1; i< iterable.length; i++){
if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
alert(doit(word))
for loop will not fail because unique.length is dynamic, i.e will change with addition of new elements to array.
Tested in Internet Explorer too.
Here is the link to jsfiddle: https://jsfiddle.net/kannanore/z5gbee55/
var str = "hhhhheeeelllloooooohhheeeyyy";
var strLen = str.length;
var newStr = "";
for(var i=0; i < strLen; i++ ){
var chr$ = str.charAt(i);
//if(i==0) {newStr = chr$ };
if(chr$ == str.charAt(i+1)){
strLen = str.length;`enter code here`
}else{
newStr = newStr + chr$ ;
}
}
//document.write(newStr);
console.log(newStr);
//Answer: helohey

Categories