简体   繁体   中英

Replace a string in JavaScript and PHP

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.

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

在Javascript中,您需要转义该竖线字符:

alert("data|data|data".replace(/\|/g,"<br />"))

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