-1

I want to replace whole word in a string.

Here is my code

$new_val = $val.replace(/\ba\b/, "");

It replaces a woth blank ,it is working fine but i want to use dynamic value in the place of a .how to do that?

D-Shih
  • 44,943
  • 6
  • 31
  • 51
sneha
  • 13
  • 2

1 Answers1

0

Fixed version of Shivdhwaj Pandey's answer:

$val = " a b c";
$stringToFind = "a";
var re = new RegExp("\\b" + $stringToFind + "\\b");
$new_val = $val.replace(re, "");
console.log($new_val);

Source

Kevin
  • 352
  • 2
  • 4
  • 13
  • Hi, above expression works fine but if $stringToFind is prefix with '+' then it gives error Invalid regular expression: /\b+school\b/: Nothing to repeat – sneha Mar 06 '18 at 07:05