tags:

views:

68

answers:

4

How can I replace this character | in JavaScript?

<html>
<body>

<script type="text/javascript">

var str="data|data|data";
document.write(str.replace(/|/g,"<br />"));

</script>

In the output of given code, every character has the "< br />"

I don't know what is wrong with my code.. :)

Also, for PHP, I want the function to use if the input is

|string||   

and the output should be

string

only. I want only the outer part of the string in PHP to be subtituted: ||hel||lo|| would become hel||lo.

Could I use trim()? I think trim() only applies to white spaces.

+1  A: 

In Javascript, you'll need to escape that pipe character:

alert("data|data|data".replace(/\|/g,"<br />"))
Rubens Farias
+4  A: 
Piskvor
That is not correct. In JavaScript, it will only replace the first occurrence of `|`, you *have* to use regular expressions here.
Felix Kling
i want only the outer part of the string in php to be subtituted.. like "||hel||lo||" and the output would be "hel||lo"
vrynxzent
@vrynxzent: You can use `trim()` for this, see my answer.
Felix Kling
@Felix Kling: good catch, edited.
Piskvor
+2  A: 

you need to escape the | character because it is used as OR in regex /a|b/ matches either a OR b. Try /\|/

Edit: To achieve wour last goal try doing it this way (alot of regex,I know):

document.write(str.replace(/(\|)+$/g,"").replace(/^(\|)+/g,"").replace(/(\|)+/g,"<br />"));
Falle1234
thank you for the answers.. :) how about for the php?
vrynxzent
+3  A: 

JavaScript:

You have to escape the pipe symbol:

document.write(str.replace(/\|/g,"<br />"));
//                       ---^

PHP:

You can pass another parameter to trim() that specifies which characters to remove:

$str = trim($str, '| ');

If you also want to remove the character in the middle of the string you can use str_replace():

$str = str_replace('|', '', $str);
Felix Kling