Вопрос

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;
Это было полезно?

Решение

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;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top