<在正则表达式中是空格还是不空格

时间:2017-11-14 06:55:56

标签: javascript regex

我有一个多行文本框,如果我输入以下字符串:

index a<3

2<x

使用正则表达式我需要在字符'&lt;'之后添加空格如果没有空间。 并且如果字符'&lt;'之后已经有空格然后保持,因为它不会增加额外的空间。

预期结果应为:

index a< 3

2< x

我尝试了(?<=<)(?!$) and <[^\s]+这些,但在Javascript中使用时会出现语法错误。

我可以在后端使用它们(C#),但我不想为它提出服务器请求,因为它不是一个好的选择。

3 个答案:

答案 0 :(得分:0)

您可以使用\S匹配任何非空格字符(对于否定字符类[^\s]),它是一个短处理程序。由于Javascript不支持look-behind,因此您需要匹配<符号后跟非空格字符,然后将其替换为包含<符号的空格。

str = str.replace(/<(?=\S)/g, '< ');

// or with negative lookahead
str = str.replace(/<(?!\s)/g, '< ');

var str = 'index a<3\n2<x';


console.log(
  str.replace(/<(?=\S)/g, '< '),
  '\n\n',
  str.replace(/<(?!\s)/g, '< ')
)

答案 1 :(得分:0)

请参阅以下方法 without regex (好的,split中只使用了一点正则表达式)

document.querySelector( "textarea" ).addEventListener( "blur", function(){
  var value = this.value;
  //console.log( value );
  this.value = value.split( /\n|\r/ ).map( function(item){
    //console.log( item, item.split( /<|<\s/ ) );
    return item.split( /<\s|</ ).join( "< " );
  }).join( "\n" );
})
Focus out of the below textarea to see the space added
<textarea>
index a<3 
index a<3 
</textarea>

答案 2 :(得分:0)

使用以下简单正则表达式:<\b并将其替换为<(&#39;&lt;&#39;后跟空格)

相关问题