Remove tab ('\t') from string javascript

前端 未结 2 787
长发绾君心
长发绾君心 2021-02-04 00:46

How can I remove tab from a any string on javascript?

when I get my string it comes as a buffer like this:



        
相关标签:
2条回答
  • 2021-02-04 01:17

    You need a regexp to replace all occurrences;

    content = content.replace(/\t/g, '');
    

    (g being the global flag)

    /^\t+/ restricts to replacing leading tabs only, /^\s+/ includes any leading whitespace which is what you would need for "\t\t var" -> "var"

    Update

    You haven't said how the buffer is received & what type it is, my closest guess although its a strange thing to be receiving;

    var test_buffer_array = "\x0d \x0a \x3c \x25 \x72 \x65 \x73 \x70 \x6f \x6e \x73 \x65 \x2e \x73 \x74 \x61 \x74 \x75 \x73 \x20".split(" ")
    
    translate(test_buffer_array);
    
    function translate(data) {
        var content = data.join("").replace(/^\t+/gm, '');
        print(content);
    }
    
    result: "<%response.status"
    
    0 讨论(0)
  • 2021-02-04 01:32

    The problem is probably in how you define content.

    If content=='\t session',

    `content=String(content).replace('\t','');`
    

    implies that content==' session'.

    On a side-note, the String(...) is unnecessary.

    `content=content.replace('\t','');`
    

    achieves the same result.

    Edit:

    String(array) does not work as you expect.

    You have to either perform the replace before you split the string or perform the replace on every element of the array separately.

    Instead of

    var content = data.toString().split('\r\n');
    content=String(content).replace('\t','');
    

    try

    var content = data.toString().replace('\t', '').split('\r\n');
    

    Note that replace('\t', '') will replace only the first occurrence of \t. To do a global replace, use the RegExp Alex K. suggested:

    var content = data.toString().replace(/\t/g, '').split('\r\n');
    
    0 讨论(0)
提交回复
热议问题