Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第2天 写一个方法去掉字符串中的空格 #6

Open
haizhilin2013 opened this issue Apr 17, 2019 · 168 comments
Open

[js] 第2天 写一个方法去掉字符串中的空格 #6

haizhilin2013 opened this issue Apr 17, 2019 · 168 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

写一个方法去掉字符串中的空格,要求传入不同的类型分别能去掉前、后、前后、中间的空格

@haizhilin2013
Copy link
Collaborator Author

欢迎大家展开多种不同的方法

@haizhilin2013 haizhilin2013 added the js JavaScript label Apr 18, 2019
@yxkhaha
Copy link

yxkhaha commented Apr 18, 2019

        var str = '  abc d e f  g ';
        function trim(str) {
            var reg = /\s+/g;
            if (typeof str === 'string') {
                var trimStr = str.replace(reg,'');
            }
            console.log(trimStr)
        }
        trim(str)

@qq674785876
Copy link

var trim = function(str){
return str.replace(/\s*/g,"");
}
str.replace(/\s*/g,""); //去除字符串内所有的空格
str.replace(/^\s*|\s*$/g,""); //去除字符串内两头的空格
str.replace(/^\s*/,""); //去除字符串内左侧的空格
str.replace(/(\s*$)/g,""); //去除字符串内右侧的空格

@shulandmimi
Copy link

function deleSpac(str,direction) { // 1 串的模板 2 清除哪边空格
            let Reg = '';
            switch(direction) {
                case 'left' : // 去除左边
                    Reg = /^[\s]+/g;
                    break;
                case 'right' : // 去除右边
                    Reg = /([\s]*)$/g;
                    break;
                case 'both' : // 去除两边
                    Reg = /(^\s*)|(\s*$)/g
                    break;
                default :   // 没传默认全部,且为下去除中间空格做铺垫
                    Reg = /[\s]+/g;
                    break;
            }
            let newStr = str.replace(Reg,'');
            if ( direction == 'middle' ){
                let RegLeft = str.match(/(^\s*)/g)[0]; // 保存右边空格
                let RegRight = str.match(/(\s*$)/g)[0]; // 保存左边空格
                newStr = RegLeft + newStr + RegRight; // 将空格加给清完全部空格后的字符串
            }
            return newStr;
        }

@linghucq1
Copy link

linghucq1 commented May 8, 2019

const str = '  s t  r  '

const POSITION = Object.freeze({
  left: Symbol(),
  right: Symbol(),
  both: Symbol(),
  center: Symbol(),
  all: Symbol(),
})

function trim(str, position = POSITION.both) {
  if (!!POSITION[position]) throw new Error('unexpected position value')
  
  switch(position) {
      case(POSITION.left):
        str = str.replace(/^\s+/, '')
        break;
      case(POSITION.right):
        str = str.replace(/\s+$/, '')
        break;
      case(POSITION.both):
        str = str.replace(/^\s+/, '').replace(/\s+$/, '')
        break;
      case(POSITION.center):
        while (str.match(/\w\s+\w/)) {
          str = str.replace(/(\w)(\s+)(\w)/, `$1$3`)
        }
        break;
      case(POSITION.all):
        str = str.replace(/\s/g, '')
        break;
      default: 
  }
  
  return str
}

const result = trim(str)

console.log(`|${result}|`) //  |s t  r| 

@qqdnnd
Copy link

qqdnnd commented May 16, 2019

function trimStr(str, type) {
    const regObj = {
        left: /^\s+/,
        middle: /(^\s+)(\S)|\s+(\S)/g,
        right: /\s+$/,
        both: /(^\s+)|(\s+$)/g,
        all: /\s+/g
    };
    const reg = type && regObj[type] ? regObj[type] : regObj.both;
    const replaceStr = type === 'middle' ? (m, $1, $2, $3) => $1 ? m : $3 : '';
    return str.replace(reg, replaceStr);
}
trimStr('  aa bb  cc d d ee  ','middle');

@tzjoke
Copy link

tzjoke commented May 16, 2019

  • Regex: string.replace(/\s/g, '')
  • join: string.split(' ').join('')

@yangchunboy
Copy link

var str = ' 1 2 3445 6    ';
console.log(str.split(' ').join('')) // 输出"1234456"

这样不是很简单吗 @haizhilin2013

@Hxiaongrong
Copy link

function noSpace(str){
if (!str) return ''
return str.split('').filter(item => item !== ' ').join('')
}

@Zhou-Bill
Copy link

" 123 56 ".replace(/\s+/g, "")

@likeke1997
Copy link

function trim(str) {
    return str.split(' ').join('');
}
var result = trim(' hello world, I am keke. ');
console.log(result); // helloworld,Iamkeke. 

@myprelude
Copy link

myprelude commented Jun 13, 2019

 str.trim()

@wanghaooo
Copy link

const trim = (str) => str.split('').filter((item) => item !== ' ').join('');

@Damon99999
Copy link

str.replace(/[ ]/g, "");

@AricZhu
Copy link

AricZhu commented Jun 18, 2019

function removeSpace (str, type) {

if (type === 'before') {
	// 递归去除字符串前面的空格
	return (str && str[0] === ' ')? removeSpace(str.substring(1), type): str;
} else if (type === 'after') {
	// 递归去除字符串后面的空格
	return (str && str[0] && str[str.length - 1] === ' ')? removeSpace(str.substring(0, str.length-1), type): str;
} else if (type === 'before-after') {
	// 递归去除字符串前后的空格
	return (str = removeSpace(str, 'before')) && (str = removeSpace(str, 'after'));
} else if (type === 'between') {
	// 递归去除字符串中间的空格
	// 首先找到 'x y'类型的字符位置
	let x = y = 0;
	outer:
	for (let i = 0; i < str.length - 1; i ++) {
		if (str[i] !== ' ' && str[i+1] === ' ') {
			x = i;
			let j = i + 2;
			while(j < str.length && str[j] === ' ') {
				j++;
			}
			if (j < str.length) {
				y = j;
			}
			break outer;
		}
	}
	return y !== 0? removeSpace(str.substring(0, x + 1) + str.substring(y), type): str;
} else {
	throw new Error('类型错误!');
}

}

@persist-xyz
Copy link

myTrim: (str) => {
        // 1 去除所有空格
        str = str.replace(/\s*/g, '')
        // 2去除所有空格
        str = str.split(' ').join('')


        // 1 去除开头空格
        str = str.replace(' ', '')
        // 2 去除开头空格
        str = str.replace(/^\s*/, '')


        // 1 去除结尾空格
        str = str.replace(/\s*$/, '')


        // 1 去除中间空格
        while(str.match(/\w\s+\w/)) {
            str = str.replace(/^\s*|\s*$/, '')
        }
        
        return str
    }

@Konata9
Copy link

Konata9 commented Jul 1, 2019

正则不是很熟,感觉中间的空格也能用正则去掉

const trimString = ({str = "", position = "both"}) => {
  if (!str) {
    return str;
  }

  const removePos = {
    left: () => str.replace(/^\s+/, ""),
    right: () => str.replace(/\s+$/, ""),
    both: () => str.replace(/(^\s+)|(\s+$)/g, ""),
    // 这个方法在字符串中间有多个空格时会有问题
    // middle: () =>
    //   str
    //     .split(" ")
    //     .map((item) => (item ? item : " "))
    //     .join(""),
    // 下面这种正则更优雅
    // middle: () => {
    //   let result = str;
    //   while (/\w+\s+\w+/.test(result)) {
    //     result = result.replace(/(\w+)\s+(\w+)/, '$1$2');
    //   }
    //   return result;
    // },
    // 一行正则
    // middle: () => str.replace(/\b\s*\b/g,''),
    // 普通方法
    middle: () => {
      const leftSpace = str.match(/^\s+/)[0];
      const rightSpace = str.match(/\s+$/)[0];
      return leftSpace + str.split(" ").join("") + rightSpace;
    },
    all: () => str.split(" ").join("")
  };

  return removePos[position]();
};

const a = "  12a b       cde fff ";
console.log("trim left:", trimString({str: a, position: "left"}));
console.log("trim right:", trimString({str: a, position: "right"}));
console.log("trim middle", trimString({str: a, position: "middle"}));
console.log("trim both:", trimString({str: a}));
console.log("trim all:", trimString({str: a, position: "all"}));

@alowkeyguy
Copy link

不太明白为什么要分左中右,正着是贪婪的

function trim (str) {
	let reg = /\s+/g
	return str.replace(reg, '')
}

@DarthVaderrr
Copy link

var str = ' 1 2 3445 6    ';
console.log(str.split(' ').join('')) // 输出"1234456"

这样不是很简单吗 @haizhilin2013

这个如果遇到连续的空格呢

@boboyu
Copy link

boboyu commented Jul 3, 2019

String.prototype.myTrim = function(option){
  var _this = this;
  var fn = {
    front:function(){
      return _this.replace(/^\s+/,'')
//       return _this.trimLeft()//或_this.trimStart() ie不支持
    },
    end:function(){
      return _this.replace(/\s+$/,'')
//       return _this.trimRight()//或 _this.trimEnd() ie不支持
    },
    frontEnd:function(){
      return _this.replace(/^\s+|\s+$/g,'');
//       return _this.trim()//--包括所有的空格字符 (space, tab, no-break space 等)以及所有的行结束符(如 LF,CR)
//       return _this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
/* 某些软件,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM),
转码后是“\uFEFF”,因此我们在读取时需要自己去掉这些字符。
“\xA0”其实就是HTML中常见的“&nbsp;” */
    },
    content:function(){
      var mStr = this.all();
      var lStr = _this.match(/^\s+/)[0];
      var rStr = _this.match(/\s+$/)[0]
      return lStr + mStr + rStr
    },
    all:function(){
      return _this.replace(/\s+/g,'')
    }
  }
  return fn[option]();
}
var str = '  s t  r  ';
var _str = {}
_str.front = str.myTrim('front')
_str.end = str.myTrim('end')
_str.frontEnd = str.myTrim('frontEnd')
_str.content = str.myTrim('content')
_str.all = str.myTrim('all')
console.log(_str)

全角空格还需要匹配“\u3000”

@haizhilin2013
Copy link
Collaborator Author

@boboyu 格式化下代码吧,用markdown的语法

@chenliwen123
Copy link

var str = ' 1 2 3445 6    ';
console.log(str.split(' ').join('')) // 输出"1234456"

这样不是很简单吗 @haizhilin2013

这个如果遇到连续的空格呢

连续的也没有问题啊

@Azathoth-H
Copy link

Azathoth-H commented Jul 12, 2019

let str = '21 sdf asdf 123 '
str.replace(/ /g, '')
str.split(' ').join('')

@shufangyi
Copy link

function trim(str, types = ['start', 'end', 'middle']) {
  types.forEach(type => {
    switch (type) {
      case 'start':
        str = str.replace(/^\s*/, '')
        break
      case 'end':
        str = str.replace(/\s*$/, '')
        break
      case 'middle':
        while (str.match(/(\S)\s+(\S)/)) {
          str = str.replace(/(\S)\s+(\S)/g, '$1$2')
        }
        break
      default:
        break
    }
  })
  return str
}

@goldEli
Copy link

goldEli commented Jul 24, 2019

var removeSpace1 = (str, type) => {
  if (!str) return 
  switch(type){
    case 'ALL':
      return str.replace(/\s/g, '')
    case 'TRIM_HEAD_AND_TAIL':
      return str.replace(/^\s*|\s*$/g, '')
    case 'TRIM_HEAD':
      return str.replace(/^\s*/g, '')
    case 'TRIM_TAIL':
      return str.replace(/\s*$/g, '')
    default:
      return str
  }
}

@ZhaoYu8
Copy link

ZhaoYu8 commented Jul 25, 2019

// 我看大家基本上都用正则解决的,想了一下js提供的字符串方法也能解决。简洁程度比不上正则。
let str = '  a   b  c  ';
let delBlank = (str, type) => {
  let count = 0,_str = str.split(''), arr = [];
  _str.map((r, i) => {
    if (r !== " ") { // 主要是为了取第一个,最后一个不是" "的下标
      !count ? (arr[0] = i,count++) : arr[1] = i + 1
    }
  })
  switch (type) {
    case 'all':
      return str.split(' ').join('')
      break
    case 'left':
      return str.slice(arr[0])
      break
    case 'right':
      return str.slice(0, arr[1])
      break
    case 'centre':
      // 字符串拼接:左边的空格 + 去除前后空格后的字符串,然后再删除所有的空格 + 尾部的空格
      return str.slice(0, arr[0]) + str.slice(arr[0], arr[1]).split(' ').join('') + str.slice(arr[1], _str.length)
      break
    default:
      return str;
      break
  }
}
console.log(delBlank(str, 'centre'))

@IanSun
Copy link

IanSun commented Jul 26, 2019

注意审题啊,要求的是去掉空格,不是去掉空白字符

const trim = ( () => {
  const ALL      = Symbol( `ALL` );
  const END      = Symbol( `END` );
  const INSET    = Symbol( `INSET` );
  const START    = Symbol( `START` );
  const SURROUND = Symbol( `SURROUND` );

  const WHITESPACE = `\u0020`;
  const REGEXP = {
    [ ALL ]      : new RegExp( `${ WHITESPACE }+`, `gu` ),
    [ END ]      : new RegExp( `${ WHITESPACE }+$`, `u` ),
    [ INSET ]    : new RegExp( `(?<!^|${ WHITESPACE })${ WHITESPACE }+(?!$|${ WHITESPACE })`, `gu` ),
    [ START ]    : new RegExp( `^${ WHITESPACE }+`, `u` ),
    [ SURROUND ] : new RegExp( `^${ WHITESPACE }+|${ WHITESPACE }+$`, `gu` ),
  };

  function trim ( string = ``, type ) {
    return REGEXP[ type ] ?
      string.replace( REGEXP[ type ], `` ) :
      string;
  }

  trim.ALL      = ALL;
  trim.END      = END;
  trim.INSET    = INSET;
  trim.START    = START;
  trim.SURROUND = SURROUND;

  return trim;
} )();
const string = '  abc d e f  g ';

console.log( JSON.stringify( trim( string, trim.ALL ) ) );
console.log( JSON.stringify( trim( string, trim.END ) ) );
console.log( JSON.stringify( trim( string, trim.INSET ) ) );
console.log( JSON.stringify( trim( string, trim.START ) ) );
console.log( JSON.stringify( trim( string, trim.SURROUND ) ) );

@Cillivian
Copy link

 str.trim()

这个是删去两端的空格,而不会删去字符中间的空格:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

@LvyYoung
Copy link

let str = '  abcde fgh ijk ';
console.log("    原字符串:" + str);
console.log("  去掉左空格:" + str.replace(/^\s*/g, ''));
console.log("  去掉右空格:" + str.replace(/\s*$/g, ''));
console.log("去掉左右空格:" + str.replace((/^\s*/g|/\s*$/g), ''));
console.log("去掉所有空格:" + str.replace(/\s*/g, ''));

@WangXi01
Copy link

str.replace(/\s*/g,"")

@web-ma-hub
Copy link

function removeSpace(str, type = 'all') {
  if (typeof str !== 'string' || !str.length) return str
  let reg
  if (type === 'all') {
    reg = /\s/g
  } else if (type === 'left') {
    reg = /^\s+/
  } else if (type === 'right') {
    reg = /\s+$/
  } else if (type === 'middle') {
    reg = /\b\s*\b/g
  } else if (type === 'lr') {
    reg = /^\s+|\s+$/g
  } else {
    reg = ''
  }
  return str.replace(reg, '')
}

@lv107w
Copy link

lv107w commented Aug 8, 2022

str.replace(/\s*/g,"")

@superyeda
Copy link

    function dealText(){
        let text=answer.innerHTML=inputText[0].value
        let reg=/\s/g
        answer.innerHTML=text.replace(reg,'')
    }

@wyy-g
Copy link

wyy-g commented Sep 6, 2022

function deleteSpace(str){
str.replace(/\s+/, '');
}

@Bruce-shuai
Copy link

let str = ' a s ddd '
str.replaceAll(' ', '')

@luise2019
Copy link

function strFormat(str) {
return str.split(' ').join('');
}

@GitHubJiKe
Copy link

image

@wl2282589971
Copy link

function trim(str) {
return str.replace(/^\s+|\s+$/g, "");
}

@wl2282589971
Copy link

function trim(str) {
return str.replace(/\s/g, "");
}

@ANLX666
Copy link

ANLX666 commented Dec 23, 2022

var a=" a";
var b = "b "; 
var c = " d "; 
var d = " " ;
var s = "" ;
s= s ;
function quchu( s ) { 
    for(let i = 0 ;i <s.length ;i ++ ) { 
      if (s[i]==" ") { 

      }
      else { 
        console.log(s[i]);
      }
    }
}
quchu(s);

@ANLX666
Copy link

ANLX666 commented Dec 23, 2022

let b="<a>        测试1</a><a>          测试2</a><a> 测试3   </a>"
 
console.log(b.replace(/\s*/g, ''))
 
输出:  
<a>测试1</a><a>测试2</a><a>测试3</a>

@caohuili
Copy link

caohuili commented Feb 17, 2023

// 写一个方法去掉字符串中的空格,要求传入不同的类型分别能去掉前、后、前后、中间的空格
function delSpaceStr(str,spacePosType="side"){
let reg = new RegExp()
switch (spacePosType){
case "left":
reg = /^\s+/g
return str.replace(reg,"")
case "right":
reg = /\s+$/g
return str.replace(reg, "")
case "side":
reg = /^\s+|\s+$/g
return str.replace(reg, "")
case "center":
reg = /(\S)(\s+)(\S)/g
return str.replace(reg, "$1$3")
default:
reg = /\s+/g
return str.replace(reg,)
}
}

var str1 = ' aa bbbd ccc de '
console.log(delSpaceStr(str1))

@yang255087
Copy link

str.replaceAll(' ','');

@Hanies11
Copy link

Hanies11 commented Mar 9, 2023

let str = ' 1 2 3 4 5 6 7 8 9 1 0 ';
let arr = str.split(" ").join("");

@Frontendnightmare
Copy link

const removeSpace = (str) => {//去除所有空格
return str.split(" ").join('');

}

@13714273163
Copy link

13714273163 commented Jun 23, 2023 via email

@clairyitinggu
Copy link

let str = "hello world";
let newStr = str.replace(/\s/g, '');

@YgTrace
Copy link

YgTrace commented Jul 13, 2023

function clearSpaceFromString (type, str) {
  let newStr = ''
  switch (type) {
    case 'all':
      newStr = str.replaceAll(' ', '')
      break;
    case 'both':
      newStr = str.trim()
      break;
    case 'start':
      str[0] === ' ' ?  newStr = str.replace(' ', '') : newStr = str
      break;
    case 'end':
      str[str.length - 1] === ' ' ?  newStr = str.replace(/\s*$/, '') : newStr = str
      break;
    default:
      newStr = str
      break;
  }
  return newStr
}

@gavawu
Copy link

gavawu commented Sep 7, 2023

const str  = ' 23  33 '
const arr = str.split('')
console.log(arr.filter(i=>i!=' ').join(''))

@0726m
Copy link

0726m commented Sep 22, 2023

function removeSpace(str){
    return str.replace(/\s/g,' ');
}
const str = ' Hello   World    ';
const result = removeSpace(str);
console.log(result)

@lili-0923
Copy link

const str = " ab cd e f 4g h ";
console.log(str.replace(/\s+/g, "")); // abcdef4gh

@13714273163
Copy link

13714273163 commented Feb 1, 2024 via email

@angrybird233
Copy link

function removeStringSpace(string) {
return string.replace(/\s/g, "");
}

@13714273163
Copy link

13714273163 commented Feb 26, 2024 via email

@lxt-ing
Copy link

lxt-ing commented Feb 26, 2024 via email

@admiral20
Copy link

admiral20 commented Mar 14, 2024

image

@xiaotangaichihuluobo
Copy link

1、去除两端空格
const str = " Hello World! ";
const trimmedStr = str.trim(); // "Hello World!"
2.去除中间的空格
str.replace(/\s+/g,'')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests