Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can not make string library 'replace()' work 1

Status
Not open for further replies.

lcs01

Programmer
Aug 2, 2006
182
US
I can not believe why such a simpel js code would not work!!

Code:
<html>
<head>
<script type="text/javascript">//<![CDATA[
function clean(str) {
  var regex = /\s*/;
  //var regex = /\s+/;
  var nstr = str.replace(regex, '^');
  alert('str = #' + str + '#, nstr = #' + nstr + '#');
//  document.write('str = #' + str + '#, nstr = #' + nstr + '#');
}
//]]></script>
</head>
<body>
<form method="post" action="#" name="theForm">
Enter something:
<input type="text" onchange="clean(document.getElementById('userinput').value);" id="userinput" />
<input type="submit"/>
</form>
</body>
</html>

I want to replace all spaces with '^'. As you can see here I have tried both '\s*' & '\s+'. Neither worked! What do I miss here?

Thank you!
 
Do this, /s is really more than just spaces, and you need to make your replace a global replace, this can be done without need to specify a regExp variable, since the code is minimal.
Code:
function clean(str) {
  [!]var nstr = str.replace(\ \g, '^');[/!]
  alert('str = #' + str + '#, nstr = #' + nstr + '#');
//  document.write('str = #' + str + '#, nstr = #' + nstr + '#');
}

[monkey][snake] <.
 
Thank you, monksnake!

But why did '\s' not work? BTW, '\s' is more than just ' ', so it's better to work!

 
But why did '\s' not work?

Because you didn't specify a global replace.
Also, with the * in there, you would match anything, so the * shouldn't be used.

Code:
var regex = /\s/[!]g[/!];

If you needed to replace every instance of spaces consecutive and non-consecutive, you would use the + instead of the *.

Code:
var regex = /\s[!]+[/!]/[!]g[/!];

In this case the string:

"T S DS E"

would become:

"T^S^DS^E"

with the replace.



[monkey][snake] <.
 
Sorry, I only read your code but not your explaination.

I understand it now. Thank you again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top