1

I have a bit difficult to do a string replace with the following.

I would like to replace the - with – but when encounter - surround with number (either left or right), just remove the white space. Just wondering if it's possible?

Original--------------------------

These days, family bonding isn’t as simple as it sounds. We all lead hectic lives, and all family members - even small kids - can have busy schedules. Plus, constant distractions from TV and social media can get in the way of meaningful interactions between parents and kids, as well as between siblings. To celebrate National Families Week (15th - 21st May), we’ve put together these ten steps for better family bonding.

After filter--------------------------

These days, family bonding isn’t as simple as it sounds. We all lead hectic lives, and all family members – even small kids – can have busy schedules. Plus, constant distractions from TV and social media can get in the way of meaningful interactions between parents and kids, as well as between siblings. To celebrate National Families Week (15th-21st May), we’ve put together these ten steps for better family bonding.

What i got so far.--------------------------

var data = document.getElementById('textarea').value;

var re = /\s-\s/gi;
var newstr = data.replace(re, " – ");

document.getElementById('textareaFilter').value = newstr;

1 Answer 1

2

You could do this using a variation of the replace() method that accepts a function to process the matched string and an extra step.

Here's a jsFiddle example and the most relevant code:

var text = 'These days, family bonding isn’t as simple as it sounds. We all lead hectic lives, and all family members - even small kids - can have busy schedules. Plus, constant distractions from TV and social media can get in the way of meaningful interactions between parents and kids, as well as between siblings. To celebrate National Families Week (15th - 21st May), we’ve put together these ten steps for better family bonding.';
var re1 = /(\d\s-\s|\s-\s\d|\d\s-\s\d)/gi
var re2 = /\s-\s/gi;
var newstr = text.replace(re1, function(match) { 
    return match.replace(/\s/gi, '');
});
newstr = newstr.replace(re2, " – ");
document.getElementById('textareaFilter').value = newstr;
Sign up to request clarification or add additional context in comments.

1 Comment

didn't know you can do a match within the replace, that's awesome thanks for the code and also a lesson :)

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.