Replace all left spaces with a specific string

前端 未结 5 510
时光说笑
时光说笑 2020-12-19 11:18

I have following code to replace left spaces with a specific string but, It is not working as I want.

相关标签:
5条回答
  • 2020-12-19 11:47

    This will surely do in two lines:

      var str ='   asdadasdad as asdasd asasd';   
      console.log(str.trim().padStart(str.length, 'x')); 
    
    0 讨论(0)
  • 2020-12-19 11:49

    You may use a lambda function as 2nd argument of .replace:

    const s = '  asdadasdad as asdasd asasd';
    
    var repl = s.replace(/^\s+/, m => m.replace(/\s/g, 'x'));
    
    console.log(repl);

    0 讨论(0)
  • Currently you're replacing complete match with single x character but you need to repeat x to length of match,

    let str = '  asdadasdad as asdasd asasd'
    let replacedStr = str.replace(/^\s+/, (m) => 'x'.repeat(m.length))
    console.log(replacedStr)

    0 讨论(0)
  • 2020-12-19 12:00

    You may use

    .replace(/\s/gy, 'x')
    

    Here, each whitespace that is at the start of the string is replaced with x. The combination of the g (global) and y (sticky) modifiers makes it match at the start of the string, and then consecutively until no match is found.

    JS demo:

    console.log(
      '  asdadasdad as asdasd asasd'.replace(/\s/gy, 'x')
    )

    0 讨论(0)
  • 2020-12-19 12:09

    You can use a callback function to generate the same length string which contains x.

    console.log('  asdadasdad as asdasd asasd'.replace(/^\s+/, m => new Array(m.length).fill('x').join('')))


    Or alternately with positive look-behind(not supported widely, check here).

        console.log('  asdadasdad as asdasd asasd'.replace(/(?<=^\s*)\s/g, 'x'))

    0 讨论(0)
提交回复
热议问题