Trim string in JavaScript?

后端 未结 20 2394
不知归路
不知归路 2020-11-21 06:27

How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?

20条回答
  •  醉酒成梦
    2020-11-21 07:11

    Don't know what bugs can hide here, but I use this:

    var some_string_with_extra_spaces="   goes here    "
    console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
    

    Or this, if text contain enters:

    console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
    

    Another try:

    console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
    

提交回复
热议问题