1

I have the following string:

var string = "Deluxe 3 Bed  Private"

and the following code to replace the "Private" word with an empty space:

var rooms = ["Basic", "Standard", "Superior", "Deluxe", "Private"];
//var room = "room";
vwo_$(document).ready(function(){

  WRI.eventBus.on('ui:microsite:availabilityStore:refresh', function(){
    var roomName = $(".roomnamelink");
    roomName.each(function(){
      for (var i = 0; i < rooms.length; i++) {
        var pattern = "[^\s]" + rooms[i];
        var regex = new RegExp(pattern);
        string = string .replace(regex, " ");
      }
    });
  })

but my regex is probably wrong.

If the word "Private" is found in the string I want that replaced with an empty space.

var string = "Deluxe 3 Bed"
4
  • 1
    you can test the regex online. regex101.com Commented Jul 28, 2016 at 8:57
  • you want to replace each word of the array if found with a space? Commented Jul 28, 2016 at 9:06
  • 1
    jsfiddle.net/t3uor52n the regex works correctly Commented Jul 28, 2016 at 9:07
  • I want to replace any of the words found in the rooms array with an empty space Commented Jul 28, 2016 at 9:07

3 Answers 3

2

I want to replace any of the words found in the rooms array with an empty space you can use one regex for all the possible words

var regex = /\b(Basic|Standard|Superior|Deluxe|Private)\b/gi

and the use it with String#replace method

var string = "Deluxe 3 Bed  Private"
string.replace(regex, '')
Sign up to request clarification or add additional context in comments.

Comments

1

You could search for white space and the word, you want to replace.

var re = /[\s]*?private/gi,
    str = 'Deluxe 3 Bed  Private',
    subst = ''; 
 
var result = str.replace(re, subst);
console.log('#' + result + '#');

Comments

1

you can do it by using very simple code like below:

 var string = "Deluxe 3 Bed  Private"
 //checking whether private is in String or not.

 if (wordInString(string, 'Private')) 
   { 
    string = string.replace('Private', ' ');
   }
   alert(string);

        function wordInString(s, word) {
            return new RegExp('\\b' + word + '\\b', 'i').test(s);
        }

that's all.. :)

Comments

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.