Exemplo n.º 1
0
        /// <summary>
        /// Returns a copy of this string with text replaced using a replacement function.
        /// </summary>
        /// <param name="thisObject"></param>
        /// <param name="substr"> The text to search for. </param>
        /// <param name="replaceFunction"> A function that is called to produce the text to replace
        /// for every successful match. </param>
        /// <returns> A copy of this string with text replaced. </returns>
        public static string Replace(string thisObject, string substr, FunctionInstance replaceFunction)
        {
            // Find the first occurrance of substr.
            int start = thisObject.IndexOf(substr, StringComparison.Ordinal);

            if (start == -1)
            {
                return(thisObject);
            }
            int end = start + substr.Length;

            // Get the replacement text from the provided function.
            var replaceText = TypeConverter.ToString(replaceFunction.CallFromNative("replace", null, substr, start, thisObject));

            // Replace only the first match.
            var result = new System.Text.StringBuilder(thisObject.Length + (replaceText.Length - substr.Length));

            result.Append(thisObject, 0, start);
            result.Append(replaceText);
            result.Append(thisObject, end, thisObject.Length - end);
            return(result.ToString());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Returns a copy of the given string with text replaced using a regular expression.
        /// </summary>
        /// <param name="input"> The string on which to perform the search. </param>
        /// <param name="replaceFunction"> A function that is called to produce the text to replace
        /// for every successful match. </param>
        /// <returns> A copy of the given string with text replaced using a regular expression. </returns>
        public string Replace(string input, FunctionInstance replaceFunction)
        {
            return(this.m_value.Replace(input, match =>
            {
                // Set the deprecated RegExp properties.
                this.Engine.RegExp.SetDeprecatedProperties(input, match);

                object[] parameters = new object[match.Groups.Count + 2];
                for (int i = 0; i < match.Groups.Count; i++)
                {
                    if (match.Groups[i].Success == false)
                    {
                        parameters[i] = Undefined.Value;
                    }
                    else
                    {
                        parameters[i] = match.Groups[i].Value;
                    }
                }
                parameters[match.Groups.Count] = match.Index;
                parameters[match.Groups.Count + 1] = input;
                return TypeConverter.ToString(replaceFunction.CallFromNative("replace", null, parameters));
            }, this.Global ? int.MaxValue : 1));
        }