开发者

Replace Lessthan and character with Lessthan space and character in javascript

In my text box, i s开发者_开发百科hould find (<LessThan Symobl> <character>) and replace with (<LessThan Symbol <space> <character>)

Example:

Input:

abc<xyz abc <abc

output:

abc< xyz abc < abc

From a string, i should find ([LessThanSymbol] [character]) and replace with ([LessThanSymbol] [space] [Character] ) in javascript


You can use a regular expression to find all < character that are followed by a non-space character, and insert a space:

s = s.replace(/<([^ ])/g, '< $1');


s = s.replace(/<(?=\S|$)/g, "< ");

What this means:

  • You can guess what .replace() does and what the < represents. :-)
  • (?=...) is a "positive look-ahead" — it means "followed by".
  • \S matches any non-whitespace character (anything other than spaces, non-breaking spaces, tabs, carriage returns, and newlines).
  • $ matches the end of the string.
  • /.../g performs a global search/replace.

Using the look-ahead prevents you from having to use a capturing group ($1), using \S fixes your newline problem, and using $ keeps you from having a similar problem if the string ends with a less-than.

>>> "<foo < bar <\tbaz <\rquux <\nquuux <".replace(/<(?=\S|$)/g, "< ")
"< foo < bar <\tbaz <\rquux <\nquuux <"


The best I've found is this :

s = s.replace(/<(?!\s)(?!$)/g,'< ');

It means:

  • (?!\s) - not followed by a whitespace (Negative Lookahead)
  • (?!$) - not followed by the end of the string (Negative Lookahead)

You can also use a split() then a join() :

'abc<xyz abc <abc'.split('<').join('< ')

But there is a problem with this method : the trail character which is completed with a non necessary space.

'abc<xyz abc <abc<'.split('<').join('< ')

gives this result

'abc< xyz abc < abc< '


Try something like...

var string_variable;
string_variable = "Replace text using javascript replace function within a javascript string variable";
string_variable = string_variable.replace(/javascript/g, "js");
alert(string_variable);

(see: http://www.kodyaz.com/articles/replace-all-occurrences-of-string-using-javascript-replace-function.aspx)


I found answer for this.

s= s.replace(/<([^ \n])/g, '< $1');

It inserts space after lessthan for all the occurances of lessthan followed by (nonspace and non new line)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜