skrttt44
skrttt44

Reputation: 39

upperCase even characters and lowerCase odd characters in each element of an array in JavaScript

I need to upperCase even characters and lowerCase odd characters in each element of an array so that with the input of 'This is a test' the output would be 'ThIs Is A TeSt' (excluding spaces so that each word begins with a capital letter).

Here's what I've come up with so far:

function toWeirdCase(string) {
  var reg = /\b(?![\s.])/
  var res = string.split(reg)
  var newArr = []

  for (let k = 0; k < res.length; k++) {
    for (let j = 0; j < res[k].length; j++) {
      if (j % 2 == 0) {
        res[k].charAt(j).toUpperCase()
      } else {
        res[k].charAt(j).toLowerCase()
      }
    }
    newArr.push(res[k])
  }
  return newArr.join('')
}

console.log(toWeirdCase('This is a test'))

It doesn't work as intended and due to lack of experience I can't tell what's missing. Could you please help me out with this? Thank you.

Upvotes: 0

Views: 2451

Answers (7)

Ketan Ramteke
Ketan Ramteke

Reputation: 10665

You can use a simple map function to do that:

"This is a test"
   .split("")
   .map((s, i) => (i % 2 == 0 ? s.toUpperCase() : s))
   .join("");

Array.prototype.map()

Upvotes: 0

Akrion
Akrion

Reputation: 18525

You can use Array.map and String.split, String.join to get that result. Map through the words and then trough each character and if even uppercase it else lowercase it.

const up = string => 
  string.split(' ')
  .map(word => word.split('')
    .map((chr, i) => chr[i%2 ? 'toLowerCase' : 'toUpperCase']()).join('')
  ).join(' ')

console.log(up('This is a test'))

You can also solve it with only one Array.map and Array.reduce:

const chg = wrd => wrd.split('').map((c,i) => c[i%2 ? 'toLowerCase' : 'toUpperCase']()).join('')
const up = str => str.split(' ').reduce((r,c) => r.concat(' ', chg(c)), '')

console.log(up('This is a test'))

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37745

You can try this

let str = "This is a test";

let op = str.split(' ').map((a,i)=>a.split('').map((e,i)=>i%2==0 ? e.toUpperCase() : e.toLowerCase()).join('')).join(' ');

console.log(op)

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192132

You can use String.replace() with an external variable to decide if the text should be upper or lower case:

function toWeirdCase(string) {
  let uppercase = true;
  return string
    .replace(/./g, c => {
      const current = uppercase;
      
      uppercase = c === ' ' ? true : !uppercase;
    
      return current ? c.toUpperCase() : c.toLowerCase();
    });
}

console.log(toWeirdCase('This is a test'))

Upvotes: 0

Get Off My Lawn
Get Off My Lawn

Reputation: 36331

We can use a basic map to achieve this, and then use modules to choose upper/lower case odd/even values

  1. Split each word
  2. Split each letter in each word
    1. Use modulus on the word, not the sentence
  3. Join the word back together
  4. Join the sentence back together

function toWeirdCase(str){
  return str.split(' ').map(word =>
    word.split('').map((itm, idx) => idx % 2 ? itm.toLowerCase() : itm.toUpperCase()).join('')
  ).join(' ')
}

console.log(toWeirdCase('This is a test'))

Upvotes: 0

Jared Smith
Jared Smith

Reputation: 21955

Golfier version:

input
  .split(/\s+/)
  .map(wrd => wrd
    .split('')
    .map((c, i) => i % 2 ? c.toLowerCase() : c.toUpperCase())
    .join(''))
  .join(' ');

If you don't care about line length, it's a one-liner.

Upvotes: 0

Barmar
Barmar

Reputation: 781503

toUpperCase doesn't modify the string in place (JavaScript strings are immutable). You need to assign the result back to a variable.

function toWeirdCase(string) {
  var reg = /\b(?![\s.])/
  var res = string.split(reg)
  var newArr = []

  for (let k = 0; k < res.length; k++) {
    let newString = "";
    for (let j = 0; j < res[k].length; j++) {
      if (j % 2 == 0) {
        newString += res[k].charAt(j).toUpperCase()
      } else {
        newString += res[k].charAt(j).toLowerCase()
      }
    }
    newArr.push(newString)
  }
  return newArr.join('')
}

console.log(toWeirdCase('This is a test'))

Upvotes: 0

Related Questions