admin管理员组

文章数量:1356067

I am getting a string which is nothing but innerHTML, and so it has instances of  . I need to trim the string such that the trailing   alone are removed. Tried this:

var text;
text = txtInnerHTML.replace(/( )*/g,"");

This removes all instances of   which is not desired.. Only the trailing   instances may be which may be zero or more need to be removed.

I am getting a string which is nothing but innerHTML, and so it has instances of  . I need to trim the string such that the trailing   alone are removed. Tried this:

var text;
text = txtInnerHTML.replace(/( )*/g,"");

This removes all instances of   which is not desired.. Only the trailing   instances may be which may be zero or more need to be removed.

Share Improve this question edited Jun 8, 2010 at 6:38 ria asked Jun 8, 2010 at 6:26 riaria 7,98412 gold badges42 silver badges46 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Try txtInnerHTML.replace(/( )+$/g,"");

Use the end of string anchor

text.replace(/( )+$/, '');

I remembered which one is which by the mnemonic *carrots are more important than money(. Weird, but it worked for me when I was learning. It basically says ^ is the start anchor and $ is the end anchor. Probably doesn't make much sense out of localizations that use $ for money value.

text = txtInnerHTML.replace(/( )*$/,"")

txtInnerHTML.replace(/( |\s)$/,"");

$
Matches the ending position of the string or the position just before a string-ending $newline. In line-based tools, it matches the ending position of any line.
wikipedia

Don't forget about simple space " ". Regular expression above removes   or " " in the end of string

本文标签: Javascript to remove trailing ampnbspStack Overflow