Sandy505
Sandy505

Reputation: 888

Javascript Replace number with number in a string

Logic : To extend the month validity of a product from 'x' months to 'y' months

ARRAY
from_to[1] = 1 ( this is x )
from_to[2] = 6 ( this is y )

I have some text like this in variable myItem:

I have the following array :

from_to[1] = 1
from_to[2] = 6

I want to count the number of times the value contained in from_to[1] ( i.e. '1') exists in the text. In case of above text it should be '2' times.I want to replace these values with the value contained in from_to[2]

Office 1 mo - Rs. 2500/mo

Skype 1 mo - Rs. 1190/mo

when i am using this code :

var myItem = document.getElementById('itemsdesc').innerHTML;        
alert (myItem.match(new RegExp(from_to[1],"gi")).length);

This returns me 5 !! ( i can undertand that it also matches the '1's in the price part ) How to prevent that ?

DESIRED OUTPUT : ( after replacing )

i am a newbie to regex.......

Upvotes: 0

Views: 640

Answers (2)

jabclab
jabclab

Reputation: 15042

I think you're just missing a space either side of the 1 in the regex, hence why the 1 in 1190/mo is matched. Something like this will hopefully help:

var str = "Office 1 mo - Rs. 2500/mo Skype 1 mo - Rs. 1190/mo Facebook 3 mo - Rs. 1250/mo";

var from_to = ["0", "1", "6"];

var re = new RegExp("\\s" + from_to[1] + "\\s", "gi");
var x = str.replace(re, " " + from_to[2] + " ");

// x = Office 6 mo - Rs. 2500/mo Skype 6 mo - Rs. 1190/mo Facebook 3 mo - Rs. 1250/mo

Upvotes: 0

Krzysztof
Krzysztof

Reputation: 16130

Try this:

alert (myItem.match(new RegExp(' ' + from_to[1] + ' mo',"gi")).length);

Replace shouldn't be a problem now.

Upvotes: 1

Related Questions