Reputation: 147
I have a multi-line textbox, if I enter below string:
index a<3
2<x
By using regex I need to add space after character '<' if there is no space. And if already have space after character '<' then keep as it is don't add additional space.
Expected result should be:
index a< 3
2< x
I tried (?<=<)(?!$) and <[^\s]+
these but giving syntax error, when used inside Javascript.
I can use them in back end(C#) but I don't want to put server request for it, as it not a good option.
Upvotes: 1
Views: 65
Reputation: 115242
You can use \S
to match any non-space character(which is a short handler for a negated character class, [^\s]
). Since Javascript doesn't support look-behind you need to match <
symbol followed by non-space character and then replace it with space contained <
symbol.
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, '< ')
)
Upvotes: 0
Reputation: 850
Use the following simple regex: <\b
and replace it with <
('<' followed by a space)
Upvotes: 0
Reputation: 68413
See the following approach without regex (ok, only little bit of regex used in 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>
Upvotes: 1