1

I am trying to replace the string below with whitespaces using javascript

 function replaceString() { var str = "ABC**EFG"; return str.replace(/\*/g, " "); } 

I received the result as ABC EFG but I expect the result to come with two whitespace. I also tried the same thing using php str.replace but still get the same result.

Is there any other methods i can used to replace the individual asterisk with whitespace??

P/S: The return string will be used as part of the sql query


[UPDATE]

I ended up return the string without any replacement to sql, then I use sql replace function to perform replacement in the query.

7
  • 3
    It's probably replacing it with 2 spaces, but the browser is only rendering it as a single space, per HTMLs WS squashing behavior. Commented Jun 4, 2013 at 14:43
  • 1
    it does, but html only shows 1 whitespace character. use   Commented Jun 4, 2013 at 14:43
  • use   and not " " because in html many whitespaces is only one whitespace Commented Jun 4, 2013 at 14:43
  • +1 to @SeanBright. Try to use   instead. Commented Jun 4, 2013 at 14:44
  • 1
    @noobie: update your question with the exact usage that causes your error. Commented Jun 4, 2013 at 14:53

4 Answers 4

3

If you're displaying the resulting string in an HTML element then two or more whitespaces will be displayed as only one whitespace. To workaround this fact, use   instead:

return str.replace(/\*/g, ' '); 
Sign up to request clarification or add additional context in comments.

4 Comments

Should be added, this is only relevant if you print it to the html.
@WhyMe: yes, that's why I started with "if you're displaying the resulting string in an HTML element"...
but when i return the string, i only get the first portion "ABC"
Works for me. Oh, and sorry :).
0

try this

return str.replace(/\*/g, ' '); 

1 Comment

same issue as  , the string will be cut off
0

Buddy the problem is with the HTML compiler which has its own special rules of parsing So it parses multiple spaces into one.This can work for HTML only. Thats why use the GIFT tag

.

<pre> <p id="para"></p> </pre> <script> function replaceString() { var str = "ABC**EFG"; return str.replace(/\*/g," "); } document.getElementById("para").innerHTML=replaceString(); </script> <script> function replaceString() { var str1=String.fromCharCode(32,32); var str = "ABC**EFG"; return str.replace(/\*/g,str1); } alert(replaceString()); </script>

return of function from above code can be used directly in mysql...

Comments

0

Finally found the best solution, I replace those special characters using percent-encoding (URL-encoding)

for my case: str.replace(/\*/g, "%20");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.