2

I want to replace a simple text like: 1 day ago to Hace 1 dia

I have tried the following code, but it does not work:

var texto = "1 day ago";
texto = texto.replace('/\d+(?=day ago)/', "Hace $1 dia");
2
  • 3
    Remember that languages aren't really suited to be translated with regular expressions. What happens when something happened 2 days ago instead? Then the regex won't match... Commented Aug 26, 2011 at 9:45
  • @carlpett Languages certainly are suited for regex work, although you are correct that this usually happens at a lower level of morphological analysis, such as here detecting a plural noun inflection. Then you’ve considerations like how the formulaic transform “NUMBER PERIOD[lang=en] ago” => “hace NUMBER PERIOD[lang=es]” can take English PERIODs not just of days, but hours or weeks etc that you’d need to map to Spanish, or how NUMBER could be spelt out like four or even “two and a half” or 2.5 instead. Notice how the simple regex even messes up on “2.5 days ago”. Real language is hard. Commented Aug 26, 2011 at 14:12

3 Answers 3

4
var texto = "1 day ago";
texto = texto.replace(/(\d+) day(s?) ago/i, "Hace $1 dia$2");

I've expanded it a little to allow for "N days ago" as well.

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

1 Comment

But you need to grab the “s” and the end of “days” if it is there and put it back on the end of “dias”. “1 day” => “1 dia” (un dia), but “3 days” => “dias”. Just make it texto.replace(/(\d+) day(s?) ago/i, "Hace $1 dia$2").
2

Should be

texto = texto.replace(/(\d+) days? ago/, "Hace $1 dia");

3 Comments

What if more that one space between number and words "days" and "ago". Maybe it better: texto = texto.replace(/(\d+)\s+days?\s+ago/i, "Hace $1 dia");
I agree but I guess it should be not greedy, hence texto = texto.replace(/(\d+)\s+?days?\s+?ago/i, "Hace $1 dia");. But I think the asker doesn't have those scenarios, so keeping the regexp pattern simple runs much faster.
The code as written is wrong. You can’t map “3 days ago” into “hace 3 día” because you’ve lost the plural marker. You need to save the “s” and append it to “días”. Por ejemplo: texto.replace(/(\d+) day(s?) ago/i, "hace $1 día$2").
0

should be.......

/(\d+) day ago/i

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.