简体   繁体   中英

Add space to string when it includes word in array

I have a function where I am iterating through a given string, alternating the capitalisation of each character and concatenating it to variable alt .

In order to loop through this properly, I have removed spaces from the original string. But I need to add them back at the end of the function.

function alternatingCaps(str) { // 'hello world'
  let words = str.toLowerCase().split(' '); // ['hello','world']
  str       = words.join(''); // 'helloworld'
  let alt = '';
  for(let i = 0; i < str.length; i++) {
    if(i % 2 === 0)
      alt += str[i].toUpperCase();
    else
      alt += str[i].toLowerCase();
  }
  return alt;
} 

console.log(alternatingCaps('hello world'));
/* Output: "HeLlOwOrLd"
   Wanted output: "HeLlO wOrLd" */

Once alt contains a string included as a value in the words array, I want to add a space at the end of the word.

Here was my attempt:

 words.forEach(function(word) {
  if(alt.toLowerCase().includes(word) && word[word.length - 1] === alt[i].toLowerCase())
    alt += ' ';
});

It checks if any of the words in the words array are present in the alt string and if the current character iteration of the string corresponds to the last letter in the word. If so, it adds a space to the string.

But this does not work as intended.

> Output: "HeLlO wOr Ld"
> Wanted output: "HeLlO wOrLd"

I also imagine this would cause problems with duplicate letters. How can I accomplish my goal?

You shouldn't join your words. Keep them as separate elements in the words array then you can loop through that array applying you function to each element.

function alternatingCaps(str) { // 'hello world'
  let words = str.toLowerCase().split(' '); // ['hello','world']

  const alts = words.map(word => capitalizeEvens(word));
  return alts.join(' ');

  function capitalizeEvens(word) {
    let alt = '';
    for(let i = 0; i < word.length; i++) {
      if(i % 2 === 0)
        alt += word[i].toUpperCase();
      else
        alt += word[i].toLowerCase();
    }
    return alt;
  } 

console.log(alternatingCaps('hello world'));

You can iterate through your string one char at a time. Then, check whether the characters is an actual word character. If so, alternate the capitalization, if not, add it to the output as it is:

function altCaps(input) {
  var result = '';
  var cap = false;
  for (var i = 0; i < input.length; i++) {
    var c = input[i];
    result += /\w/.test(c) ? (cap = !cap) ? c.toUpperCase() : c.toLowerCase() : c;
  }
  return result;
}

UPDATE: The legible code

function altCaps(input) {
  var result = '';
  var cap = false;
  for (var i = 0; i < input.length; i++) {
    var c = input[i];
    if (/\w/.test(c)) {               // check if char is a "word character" (i.e. letter)
      cap = !cap;                     // toggle next capitalization
      if (cap)                        // if it should capitalize
        result += c.toUpperCase();    // add uppercase letter
      else
        result +=  : c.toLowerCase(); // add lowercase letter
    } else {
      result += c;                    // no letter, so add character as is.
    }
  }
  return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM