C_F
C_F

Reputation: 510

Javascript - Regex replace ignoring some special character

I have a string which can be..

Samsung Blu-Ray Player
Samgung Bluray player
Samsung Blu/Ray player

and I know want to find and replace bluray (later: to give it a certain color). Therefore I want to replace the word using a regex. But no idea about the regex syntax in that case. It should ignore "/" and " " and find the string, case insensitive.

Upvotes: 0

Views: 1265

Answers (3)

Herrington Darkholme
Herrington Darkholme

Reputation: 6315

/\bblu\s*[^\w]?\s*ray\b/gi

\b the word boundary gives it more conservation from matching blurayfish or so

\s* makes it white space insensitive so blu - ray will match

[^\w] matches non-word symbols like - , ? means optional

gi means all matches, case insensitive.

here is a more illustrative page, with test cases and explanation alongside.

http://regex101.com/r/gD4xS6

Upvotes: 0

aelor
aelor

Reputation: 11116

try this :

var str = "Samsung Blu-Ray Player";
var res = str.replace(/(Blu.*?ray)/gi, '<span style="color:red">$1</span>');
console.log(res);

Upvotes: 2

Matyas
Matyas

Reputation: 13702

You can replace the string using

str = str.replace(/samsung blu[^\w]?ray player/gi, 'Samsung Blu Ray player')

where

  • [^\w]? - is any nonword character (non alphanumeric)
  • The ? makes it optional
  • /gi - the flags mean global search and caseinsensitive

Upvotes: 0

Related Questions