如何删除子字符串的空格

问题描述 投票:0回答:1

我正在进行函数式编程练习,要求我用连字符替换字符串中的所有空格。如果我有一个像

This is a title
这样的字符串,输出应该是
this-is-a-title

现在,之前描述的所有情况都可以工作,但我有一个像这样的边缘情况字符串:

 Peter Is  Coming
。我想去掉
Coming
之前的空格,以便我的最终输出是
peter-is-coming
,这将是当我有一个
Peter is Coming
初始字符串且没有多余空格时的等效输出。我可以使用
Peter
方法轻松完成之前
trim
的操作。我该如何处理这种边缘情况?

注意:限制之一是不应该使用

replace
方法。

谢谢。

我的代码:

function urlSlug(title) {

  const url = title.trim().toLowerCase();
  console.log(url);

  const splitURL = url.split("");
  // console.log(splitURL);

  const urlArr = [];

  const filtered = splitURL.filter(val => {
    if (/\s/.test(val)) {
      
      urlArr.push("-");
    }
    
    else {
      urlArr.push(val);
    }
  });

  return console.log(urlArr.join(""));

}

urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone"); // a-mind-needs-books-like-a-sword-needs-a-whetstone
urlSlug("Hold The Door"); // hold-the-door 
urlSlug(" Peter is  Coming"); // peter-is--coming 

// The last output is what I get but not what I want to achieve.

javascript string trim removing-whitespace
1个回答
0
投票

您可以尝试以下方法:

function urlSlug(title) {
  //remove leading and trailing spaces
  //convert to lowercase
  const trimmedTitle = title.trim().toLowerCase();

  //split words array
  const words = trimmedTitle.split(/\s+/);

  //join the words with hyphens
  const slug = words.join("-");

  return slug;
}

console.log(urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")); // a-mind-needs-books-like-a-sword-needs-a-whetstone
console.log(urlSlug("Hold The Door")); // hold-the-door 
console.log(urlSlug(" Peter is  Coming")); // peter-is-coming

© www.soinside.com 2019 - 2024. All rights reserved.