Recently made a page containing mobile phone number, click can dial the phone, the original preparation to let the back end of each field to find out the line, the interface to the direct spell.

The string returned by the interface:

"[Wang Hai] master has received the order, contact number: 18839687266. I will contact you later. Master sign-in code is [1234], master door to enter the sign-in code can start the service.Copy the code

This makes it less convenient for us to bind the event of the call and focus on parsing the string to find the phone number.

Split method, through split to get the array containing the phone number, and then walk through the array, to the phone number elements labeled.

parseStr (str){
    const regPhone = /(1\d{10})/ 
    const list = str.split(regPhone)
    const result = []
    return list.map(c => {
        let tag
        regPhone.test(c) ? tag = 'phone' : tag = 'text'
        return {
            type: tag,
            text: c
        }
    })
}
Copy the code

After the parseStr function to get the appropriate format, loop rendering to the phone number binding event can be, the code is roughly as follows:

<view>
    <block wx:for="{{data}}" wx:for-item="i" wx:key="*this">
      <text wx:if="{{i.type === 'text'}}">{{i.text}}</text>
      <text wx:else bindtap="call(i.text)">{{i.text}}</text>
    </block>
</view>
Copy the code

Quite a simple implementation, is at first did not think of using split. Another point to note is that the regular regPhone is enclosed in parentheses. If separator is the regular expression () that contains the enclosing parentheses, then the matching result is contained in the array.

If we don’t put parentheses, we’re throwing away the numbers that we matched, and then we put parentheses, and then the array will include the numbers that we matched.