search

Home  >  Q&A  >  body text

Is it possible to change a substring within a string to a different HTML tag or attribute?

There is a React component that accepts a string as a property:

interface MyProps {
  myInput: string;
}

export function MyComponent({ myInput }: MyProps) {
   ...
   return (
     <div>
       {myInput}
     </div>
   );
};

This component is used elsewhere:

<MyComponent myInput="请通过test@test.com与我们联系" />

My question is, can we change the color of the email address in this case? For example, change it to blue.

Or better yet, wrap that text in:

<a href="mailto:test@test.com" target="_blank">
   test@test.com
</a>

Not sure if something like this is possible if the type of the property is string.

P粉852114752P粉852114752444 days ago495

reply all(1)I'll reply

  • P粉848442185

    P粉8484421852023-09-14 11:45:12

    You can do this based on the string provided, but it's easier if you provide the email address as a separate property on MyComponent.

    Without changing the components, I would use some simple regex to get the email address from a string and then you can do whatever you want.

    The following is a simple and incomplete regular expression example:

    const SUPER_SIMPLE_EMAIL_REGEX = /[a-z0-9.]{1,}@test.com/gi; // 不要使用这个
    
    export function MyComponent({ myInput }: MyProps) {
       const match = myInput.match(SUPER_SIMPLE_EMAIL_REGEX);
    
      if (!match.length) {
        return (
          <div>
            {myInput}
          </div>
        );
      }
    
      const textWithoutEmail = myInput.replace(match[0], '');
    
      return (
        <div>
          <span>{textWithoutEmail}</span>
          <a href={`mailto:${match[0]}`} target="_blank">
            match[0]
          </a>
        </div>
      );
    
    };

    This is a very simplified solution, but I think you can use it in your case.

    reply
    0
  • Cancelreply