Hightlight numbers in phone number

2019-08-15 06:12发布

This function hightlight numbers.

var hightlightPhoneNumbers = function(phoneNumber, hNumbers) {
  var splitPhoneNumber = phoneNumber.split(hNumbers);
  var result = '';

  if (splitPhoneNumber.length > 1) {
    for (var i = 0; i < splitPhoneNumber.length - 1; i++) {
      result += splitPhoneNumber[i] + '<b>' + hNumbers + '</b>';
    }
    return result + splitPhoneNumber[splitPhoneNumber.length - 1];
  }
  return phoneNumber;
};

And we can usage it as hightlightPhoneNumbers('+123456789','123').

But we have a little problem. What if phone number looks like +1 234-567-89? Ofcourse function doesnt work correct. How we can to fix it?

Hightlight means wrap numbers in tags or something. see http://jsfiddle.net/QhJWt/3/

1条回答
Rolldiameter
2楼-- · 2019-08-15 06:22
function hightlightPhoneNumbers(phoneNumber, clip) {
    var re = new RegExp(clip.split('').join('[\\s-]*'), 'gi');
    return phoneNumber.replace(re, '<b>$&</b>');
}

By the way, there is this funny non-standard method of String.prototype.bold that wraps a string into a <b></b> tag.

Demo.

查看更多
登录 后发表回答