简体   繁体   English

当字符串包含数组中的单词时向字符串添加空格

[英]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 .我有一个函数,我正在遍历给定的字符串,交替每个字符的大写并将其连接到变量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.一旦alt包含作为值包含在words数组中的字符串,我想在单词末尾添加一个空格。

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.它检查words数组中的任何words是否存在于alt字符串中,以及字符串的当前字符迭代是否对应于单词中的最后一个字母。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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