-2

Suppose we have a string: "Someone one one-way" And I want to replace THE WORD "one" with THE WORD "two".

Note: I don't want "someone" or "one-way" to change.

I tried to use str.replace(/one/g , "two"); But the result was "Sometwo two two-way"

This is not the intended result... I want to get "Someone two one-way"

ANY HELP WOULD BE APPRECIATED. THANKS IN ADVANCE....

William
  • 5
  • 6

5 Answers5

1

You can validate the spaces too:

//var str = "Someone one one-way";
var str = "one one Someone one one-way one,one";

var replace='two';
//using lookahead and lookbehind
var result= str.replace(/(?<=[^a-zA-Z-]|^)one(?=[^a-zA-Z-]|$)/gm , "two");

console.log(result);
//result: two two Someone two one-way two,two
miglio
  • 2,048
  • 10
  • 23
0
eval('STR.SPLIT(" ONE ").JOIN(" TWO ")'.toLowerCase())
Hammerbot
  • 15,696
  • 9
  • 61
  • 103
-1

try this regex:

\s(one)\s

you may add modify it for case sensitive.

-1

let input = "Someone one one-way"
output = input.split(" ").map((item)=> item ==='one'? 'two' : item).join(" ");
console.log(output)
Mohammed Ashfaq
  • 3,353
  • 2
  • 15
  • 22
-1

You can try this:

.replace(/\bone\b(?!-)/g , "two")

\b matches on a word boundary.

(?!-) is a negative lookahead because you do not want to replace one if followed by a dash. \b recognizes the dash as a word boundary.

There is another pitfall when you have something like "-one".

Use this if this is a Problem:

.replace(/[^-]\bone\b(?!-)/g , function(x){return x.substring(0,1) + 'two'})

Ideally you would use negative look ahead, but this is currently not supported by all Browsers.

Donat
  • 4,157
  • 3
  • 11
  • 26