用js替换带有空格的字符串单词

Replace a string word with empty space with js

本文关键字:字符串 单词 空格 js 替换      更新时间:2023-09-26

我有以下字符串:

var string = "Deluxe 3 Bed  Private"

以及以下代码,将"私人"一词替换为空格:

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, " ");
      }
    });
  })

但是我的正则表达式可能是错误的。

如果在字符串中找到单词"Private",我希望用空格替换它。

var string = "Deluxe 3 Bed"

我想将房间阵列中的任何单词替换为空白您可以使用一个正则表达式来表示所有可能的单词

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

并与CCD_ 1方法结合使用

var string = "Deluxe 3 Bed  Private"
string.replace(regex, '')

您可以搜索空白和要替换的单词。

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

您可以使用如下非常简单的代码:

 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);
        }

仅此而已..:)