简体   繁体   中英

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 =/

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));

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM