【问题标题】:How to make a function that find the uppercase in a string and add a space如何制作一个在字符串中查找大写并添加空格的函数
【发布时间】:2016-05-31 11:50:31
【问题描述】:

我如何做到这一点,以便该函数接受参数(品种)并搜索大写字母并在那里添加一个空格。

例如,如果我将“goldenRetriever”作为参数传递,那么函数会将其转换为“golden Retrier”

function test(breed){
    for(i=1; i<breed.length; i++){
    //wat do i do here
    }
}

【问题讨论】:

  • 这对我来说很像家庭作业。尝试搜索,我会从第一个解决方案开始:stackoverflow.com/questions/1027224/…
  • 当 .replace() 和正则表达式可以做到这一点时,我不会使用循环。

标签: javascript function uppercase


【解决方案1】:

您可以在每个大写字母之前使用带有positive lookahead/(?=[A-Z])/ 的正则表达式在每个大写字母之前split the string,然后您可以用空格将字符串重新连接在一起并将其转换为小写:

"goldenRetrieverDog".split(/(?=[A-Z])/).join(' ').toLowerCase();
// "golden retriever dog"

或者,您也可以使用.replace() method 在每个大写字母前添加一个空格,然后将字符串转换为小写:

"goldenRetrieverDog".replace(/([A-Z])/g, " $1").toLowerCase();
// "golden retriever dog"

【讨论】:

  • @Firefalcon1155 因为您没有返回字符串。应该是return breed.split(/(?=[A-Z])/).join(' ').toLowerCase();.. 看这个例子 -> jsfiddle.net/L7m2x7uL
猜你喜欢
  • 2013-05-04
  • 2020-05-07
  • 2023-02-23
  • 2016-10-18
  • 1970-01-01
  • 2016-04-23
  • 2019-07-03
  • 1970-01-01
  • 2017-07-26
相关资源
最近更新 更多