Removes the specified text from end of the string if it exists. - CSharp System

CSharp examples for System:String Strip

Description

Removes the specified text from end of the string if it exists.

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from w  ww . j a va  2s .  c o m*/

public class Main{
        /// <summary>
        /// Removes the specified text from end of the string if it exists.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public static string RemoveIfEndsWith(this string source, string text)
        {
            if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(text))
            {
                return source;
            }

            if (!source.EndsWith(text))
            {
                return source;
            }

            return source.Remove(source.Length - text.Length);
        }
}

Related Tutorials