-3

I have string in javascript, for example : "i have two PC and two laptops"; and result should be "i have three PC and three laptop".

So, I want to change all occurrences of word "two" to "three"

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Gega Gagua
  • 92
  • 9
  • Plain JavaScript is enough to do this. But show us some of your effort. – putvande Dec 05 '14 at 13:44
  • 1
    You don't need jquery for this. Use a simple replace (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace). Please use a javascript reference before asking a question – UnknownFury Dec 05 '14 at 13:46
  • (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) – szpic Dec 05 '14 at 13:46
  • @UnknownFury don't need? – Amit Joki Dec 05 '14 at 13:46

3 Answers3

0

new_string = 'pop'.replace(/two/g,'three')

this will change 'two' with 'three'

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
0

I will try to explain, replacng more then one occurence can be done with replace and a regular expression.

var input = "i have two PC and two laptops";
var output = input.replace(/two/g, "three");
Beri
  • 11,470
  • 4
  • 35
  • 57
  • You need plain JS for this. You can use JQuery to find and update DOM element with this text though:) – Beri Dec 05 '14 at 13:48
0

This will get them all:

function replace(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}


var str = 'i have two PC and two laptops';
var find = 'two';
var replace = 'three'

alert(replaceAll(find,replace,str));
baao
  • 71,625
  • 17
  • 143
  • 203