写一个方法去掉字符串中的空格 | Lacerta

写一个方法去掉字符串中的空格

回答
  1. 顺序遍历

const removeSpace = (str) => {
  let result = '';

  for (let i = 0; i < str.length; i ++) {
    (str[i] !== ' ') && (result += str[i]);
  }

  return result;
};

  1. 正则匹配 ```javascript

const removeSpace = (str) => { if (typeof str === ‘string’) { return str.replace(/\s/g, ‘’); } return str; };


</details>


## 去除字符串中最后一个指定的字符
例如, `str = "123456789abc defghi12345678 1234"`, `target = 2`, 则`result = "123456789abc defghi12345678 134"`
<details markdown="1">

<summary markdown="span">回答</summary>

```javascript

const removeLastOccurrence = (str, target) => {
  if (typeof str === 'string') {
    const regex = new RegExp(`${target}(?=[^${target}]*$)`);
    return str.replace(regex, '');
  }
  return str;
};

写一个方法把下划线命名转成驼峰命名

例如: str = 'submit_button_did_click', 转换为 result = 'submitButtonDidClick'

回答

const changeNamingConvention = (str) => {
  if (typeof str === 'string') {
    return str.replace(/(_)(\w)/g, (match, dash, characterAfterDash) => {
      return characterAfterDash.toUpperCase();
    })
  }
  return str;
};

写一个去除制表符和换行符的方法

回答

const removeTabAndReturn = (str) => {
  if (typeof str === 'string') {
    return str.replace(/[\t|\r|\n]+/g, '');
  }
  return str;
};