Problem on regular expression

C

Cylix

If there is a unlimit long textfield, the user can type free text.
It means that the client can type
I like eating very much .

How can I using regular expression to trim the spaces to single space?

Thank you
 
E

Erwin Moller

Cylix said:
If there is a unlimit long textfield, the user can type free text.
It means that the client can type
I like eating very much .

How can I using regular expression to trim the spaces to single space?

Thank you


Hi,

Here is an example that matches as you described.

Regards,
Erwin Moller

------------------------

<html>
<head>

<script type="text/javascript">
function removespaces(){
var org = document.forms.testform.inp.value;

document.forms.testform.outp.value = org.replace(/ +/g , " ");
}
</script>

</head>
<body>

<form name="testform">
INPUT:
<textarea rows=4 cols=60 name="inp"></textarea>
<br>
<input type="button" onclick="removespaces();" value="replace multiple
spaces with one">

<br>
OUTPUT:
<textarea rows=4 cols=60 name="outp"></textarea>
<br>
</form>

</body>
</html>
 
E

Evertjan.

Erwin Moller wrote on 20 jun 2006 in comp.lang.javascript:
document.forms.testform.outp.value = org.replace(/ +/g , " ");

document.forms.testform.outp.value = org.replace(/\s+/g ,' ');

Removes all kinds of white space.

\s is equivalent to [ \f\n\r\t\v].
 
L

Lasse Reichstein Nielsen

Cylix said:
further example:
I like eating very much
.

How can I using string.replace(regEx, '') and string.replace(regEx, '
') to have the result:
I like eating very much.


That's a more specific wish. Not only do you want to convert repeated
spaces to single ones, you also want to remove any space between words
and following punctuation, and all initial (and probably terminal)
spaces.

Might as well do it in three goes first:

string.replace(/^\s+|\s+$/g,"")
.replace(/\b\s+([^\w\s])/,"$1")
.replace(/\s+/," ")

The first replace removes initial and terminal whitespace.
The second replace removes spaces between a word boundary and
a non-word/non-space character.
The third replace converts single spaces to multiple spaces.

You can probably make a single regexp that does it all, but you'll
have to be inventive (and probably use advanced features like
lookahead) since you will want to replace with different strings
in each of the three cases.

But here is one attempt:

/^\s+|\s+$|\b\s+(?=[^\w\s])|\s+(?=\s)/g

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top