0

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:

  • Office 1 mo - Rs. 2500/mo

  • Skype 1 mo - Rs. 1190/mo

  • Facebook 3 mo - Rs. 1250/mo

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 )

  • Office 6 mo - Rs. 2500/mo

  • Skype 6 mo - Rs. 1190/mo

  • Facebook 3 mo - Rs. 1250/mo

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

2 Answers 2

1

Try this:

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

Replace shouldn't be a problem now.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.