Notsogood13
Notsogood13

Reputation: 109

Javascript string/variable concatenation without space

while using a ajax script, I made the php part echo a value then in the jQuery part I alert it.

So we have something like this:

<?php echo "1"; ?>

//Javascript
alert("the value is"+phpvalue);

The alert shows up like "the value is 1". Now my question is how do I remove the space between the "the value is" and +phpvalue? So it show up like "the value is1". I tried trim() on the php part but it doesn't change anything.

Apreciate any help and sorry if it is a noob question =/

Upvotes: 0

Views: 2700

Answers (2)

Kovge
Kovge

Reputation: 2019

In http response can be some other caracters than what you print. For example, if there is spaces before php tag .. BOM character in the begining of the php file... so if you trim just the variable, that does not detemrimate, that you get purely the variable on client side without junk characters.

So you should use trim on client side in javascript: For example jQuery trim (http://api.jquery.com/jQuery.trim/)

   alert("the value is"+$.trim(phpvalue));

Or use nativ js trim function from phpjsorg (http://phpjs.org/functions/trim/):

   alert("the value is"+trim(phpvalue));

Upvotes: 1

PSR
PSR

Reputation: 40318

Not sure exactly what you want but here are two situations

If you just are dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() orrtrim() to remove that.

If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " "

$foo = preg_replace( '/\s+/', ' ', $foo );

Upvotes: 0

Related Questions