o_swas wrote:
Hello,
I have a JavaScript string. I want to replace all consecutive
occurrences of whitespace characters like spaces, tabs, newlines, and
form feeds with another string.
In a regular expression, '\s' matches any whitespace character. Add the
'+' operator to make it match one or more of them, adding the 'g' flag
will make it match all instances. So:
var regExp = /\s+/g;
var aString = ' blah blah ';
alert( aString.replace(regExp,'X')); // --> XblahXblahX
Here's some play stuff:
<form action="">
<table>
<tr>
<td align="right">Replace whitespace with:</td>
<td><input type="text" name="newString" value="%"></td>
</tr><tr>
<td align="right">String:</td>
<td><textarea name="textString"
rows="20" cols="40"> Lorem ipsum dolor sit amet, consectetuer
adipiscing elit. Curabitur condimentum, orci vitae porttitor
tempus, nibh lectus viverra nunc, quis pretium turpis lacus
at magna . </textarea></td>
</tr><tr>
<td align="center"><input type="reset"></td>
<td align="center">
<input type="button" value="Replace whitespace" onclick="
var x = this.form.newString;
var y = this.form.textString;
y.value = y.value.replace(/\s+/g,x.value)
">
</td>
</tr>
</table>
</form>
[...]
--
Rob