从行首

时间:2016-12-15 13:21:07

标签: javascript regex replace split

有没有办法从一行中删除数字和周围的空格?我不想剥离我的空白。有时候我的代码冻结了,我必须用数字复制它,所以我试图用一些东西来删除每行的数字

  9 if (5==5) {
 10     console.log('Examples rock!')
 11 else {
 12     console.log('Stuff')
 13 }

之后的第1行将是if (x==5) {,其周围的数字和空格不见了。我只需要能够为1行做,因为我可以迭代

有正确的正则表达式或其他方法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式替换行。



function stripNumbers(text) {
  return text.split('\n').map(function(line) {
    let tokens = line.match(/^\s*\d+ (.*)$/);
    return tokens && tokens.length > 0 ? tokens[1] : line;
  }).join('\n');
}

let editor = document.getElementById('editor');
editor.value = stripNumbers(editor.value);

<textarea id="editor" rows="7" cols="72">
 9 if (x==5) {
 10     console.log('Examples rock!')
 11 else {
 12     console.log('Stuff')
 13 }
</textarea>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

我假设你有一个包含代码和行号的字符串,我知道当你从网页中的一些漂亮的打印输出中复制代码时会发生这种情况

"  9 if (x==5) {\n\
 10     console.log('Examples rock!')\n\
 11 else {\n\
 12     console.log('Stuff')\n\
 13 }".replace(/^\s*\d+\s/gm,"");

解释reg exp

^   - start of line
\s* - one or more white spaces
\d+ - one or more numbers
\s  - single white space

&#13;
&#13;
function remove () {
   document.getElementById("out").value = document.getElementById("in").value.replace(/^\s*\d+\s/gm,"");  
}
&#13;
textarea { width:100%; min-height: 100px; }
&#13;
<label for="in">Input</label>
<textarea id="in">
  9 if (5==5) {
 10     console.log('Examples rock!')
 11 else {
 12     console.log('Stuff')
 13 }
</textarea>
<button onclick="remove()">run</button>
<br/>
<label for="out">Output</label>
<textarea id="out"></textarea>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这将针对各种情况进行,即使有多个数字集,假设格式化,行总是在数字后面放置一个空格。我使用sed 4.2.2,但这应该适用于Perl,Python,JavaScript等。

sed -r "s/^([ \t]*[0-9])* //"

对于JavaScript,请使用string.replace(re,replacement),如下所示:

&#13;
&#13;
function removeLineNumbering(line)
{
  return line.replace(/^([ \t]*[0-9])* /gm, "");
}

document.getElementById('editor').value = removeLineNumbering(editor.value);
&#13;
<textarea id="editor" rows="5" cols="50">
  9 if (x==5) {
 10     console.log('Examples rock!')
 11 else {
 12     console.log('Stuff')
 13 }
</textarea>
&#13;
&#13;
&#13;

相关问题