Rckt
Rckt

Reputation: 185

Replacing || (concatenation) in a string

I have problem with replacing || char.

    str="Example || sentence";

    document.write(str.replace(/||/g, "+"));
// it gives me "+ +E+x+a+m+p+l+e+ +|+|+ +s+e+n+t+e+n+c+e+"

How can I fix it?

Upvotes: 0

Views: 2936

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 185893

This:

str.replace( /\|\|/g, '+' ) 

The vertical bars have are special characters inside a regular expression pattern and they have to be escaped.

Live demo: http://jsfiddle.net/mN3ft/

Upvotes: 1

js-coder
js-coder

Reputation: 8336

| is a regular expression operator, that behaves like an or. You need to escape it if you want to match it inside a String:

str = "Example || sentence";
document.write(str.replace(/\|\|/g, "+"));

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

| symbol has special meaning in regular expressions. You have to escape it.

document.write(str.replace(/\|\|/g, '+'))

Upvotes: 2

Related Questions