2

Ok, I'm actually trying to replace text.

Basically, I am needing to replace all instances of this: | with a blank string ''

However, this isn't working:

langName = langName.replace(/|/g, '');

Also, would be best if I could also replace all of these instances within the string, with a '' also:

" double quote

' single quote

/ back slash

\ forward slash

And any other html entity characters. Arrggg.

Can someone please help me here? Perhaps it can be turned into a String.prototype function so I can use it more than once?

Thanks :)

1 Answer 1

3

You need to escape | with \ like:

langName = langName.replace(/\|/g, '');

Test Case:

var langName = 'this| is | some string';

langName = langName.replace(/\|/g, '');
alert(langName);

Output:

this is some string

The reason why you need to escape | is that it is special regex character.


Alternatively, you could also use split and join like this:

langName = langName.split('|').join('');
Sign up to request clarification or add additional context in comments.

5 Comments

OMG, it's that simple... argg. Thanks, giving it a try now... lol
which is faster? split().join() or replace()?
@SoLoGHoST: I haven't benchmarked them but whenever i can use split and join, i go for them. As for speed, there shouldn't be much difference if the string isn't that huge which is the case mostly :)
So if the character | doesn't exist in the string, split and join won't work will it? So, I'm guessing that langName would return an empty string in that case?
@Sologhost: It would return string as it is, in our case this is some string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.