How can I replace this character |
in JavaScript?
<html>
<body>
<s开发者_如何转开发cript 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.
You don't need a regular expression for this - if you pass a string as the first argument to replace()
, it will be replaced literally:
var str='data|data|data';
str = str.replace('|', '');
...but it will only replace the first match. For a global replace, you need to specify the global
flag:
var str='data|data|data';
var re = new RegExp('\|','g'); // G is the 'global' flag
str = str.replace(re,'');
In PHP, str_replace() works with string literals:
$str='data|data|data';
$str = str_replace('|', '', $str);
// $str == datadatadata
If you only want to remove the outer delimiters, use trim():
$str='|||data|data||data|';
$str = trim($str,'|');
// $str == 'data|data||data';
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);
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 />"));
In Javascript, you'll need to escape that pipe character:
alert("data|data|data".replace(/\|/g,"<br />"))
精彩评论