Mich'
Mich'

Reputation: 697

JavaScript - Regex - How can I replace every char from A to Z except X?

How can I replace every letter in this string without "X" with example "-":

"XASDXDAX".replace(/([A-Z^X])/,"-") should return: "X---X--X"

Something must be wrong in the regex or what else, how can I fix it?

Upvotes: 0

Views: 239

Answers (4)

Cattode
Cattode

Reputation: 856

You may also use a negated class with the global modifier g to replace each non-X character :

"XASDXDAX".replace(/([^X])/g,"-")

Upvotes: 0

ѕтƒ
ѕтƒ

Reputation: 3647

Here is the simple regex you are searching for. Just try this

 var str="XASDXDAX".replace(/[^X]/g,"-");

Upvotes: 1

Roman Saveljev
Roman Saveljev

Reputation: 2594

"XASDXDAX".replace(/([A-WYZ])/g,"-")

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074238

You're close, you just need to add the g modifier (for "global"), and you can't express both a class and a negated class simultaneously (the ^ is only special in [] if it's the first character), so just list the ranges. Also, you don't need the capture group (the ()):

result = "XASDXDAX".replace(/[A-WY-Z]/g,"-");

Upvotes: 3

Related Questions