Replaces a string in an asset
175930
function replaceStringInAsset(asset, source, target) {
    const sourceRE = new RegExp(source, 'g');

    if (typeof asset === 'string') {
        return asset.replace(sourceRE, target);
    }

    // ReplaceSource
    if ('_source' in asset) {
        asset._source = replaceStringInAsset(asset._source, source, target);
        return asset;
    }

    // CachedSource
    if ('_cachedSource' in asset) {
        asset._cachedSource = asset.source().replace(sourceRE, target);
        return asset;
    }

    // RawSource / SourceMapSource
    if ('_value' in asset) {
        asset._value = asset.source().replace(sourceRE, target);
        return asset;
    }

    // ConcatSource
    if ('children' in asset) {
        asset.children = asset.children.map(child => replaceStringInAsset(child, source, target));
        return asset;
    }

    throw new Error(
        `Unknown asset type (${asset.constructor.name})!. ` +
            'Unfortunately this type of asset is not supported yet. ' +
            'Please raise an issue and we will look into it asap'
    );
}
100033
function replace($search,$replace){
		$this->_String = str_replace($search,$replace,$this->_String);
	}
170636
function normalizeAssets(clientLibPath, assets) {

  var list = assets;

  // transform object to array
  if (!_.isArray(assets)) {
    list = [];
    _.keys(assets).forEach(function (assetKey) {
      var assetItem = assets[assetKey];

      // check/transform short version
      if (_.isArray(assetItem)) {
        assetItem = {
          files: assetItem
        };
      }
      if (!assetItem.base) {
        assetItem.base = assetKey;
      }
      assetItem.type = assetKey;
      list.push(assetItem);
    });
  }

  // transform files to scr-dest mapping
  list.forEach(function (asset) {

    var mapping = [];
    var flatName = typeof asset.flatten !== "boolean" ? true : asset.flatten;
    var assetPath = path.posix.join(clientLibPath, asset.base);
    var globOptions = {};
    if (asset.cwd) {
      globOptions.cwd = asset.cwd;
    }

    asset.files.forEach(function (file) {
      var fileItem = file;

      // convert simple syntax to object
      if (_.isString(file)) {
        fileItem = {
          src: file
        };
      }

      // no magic pattern -> default behaviour
      if (!glob.hasMagic(fileItem.src)) {

        // determine default dest
        if (!fileItem.dest) {
          fileItem.dest = path.posix.basename(file);
        }

        // generate full path
        fileItem.dest = path.posix.join(assetPath, fileItem.dest);
        mapping.push(fileItem);
      }

      // resolve magic pattern
      else {
        var files = glob.sync(fileItem.src, globOptions);
        var hasCwd = !!globOptions.cwd;
        var dest = fileItem.dest ? path.posix.join(assetPath, fileItem.dest) : assetPath;

        files.forEach(function (resolvedFile) {

          // check 'flatten' option -> strip dir name
          var destFile = flatName ? path.posix.basename(resolvedFile) : resolvedFile;

          var item = {
            src: resolvedFile,
            dest: path.posix.join(dest, destFile)
          };

          // check "cwd" option -> rebuild path, because it was stripped by glob.sync()
          if (hasCwd) {
            item.src = path.posix.join(globOptions.cwd, resolvedFile);
          }

          mapping.push(item);
        });
      }
    });

    asset.files = mapping;
  });

  return list;
}
291742
function (token) {

			var expression = token.match[1];

			// extract arguments for the compiler
			var tagInput = token.match.input.replace(/^\s*assets\s*/mi, '').replace(/^\s*|\s*$/g, '');
			try {
				token.files = JSON.parse('[' + tagInput + ']');
			} catch (e) {
				if (tagInput.indexOf('"') === -1) {
					try {
						// try to replace single quotes with double
						token.files = JSON.parse('[' + tagInput.replace(/'/g, '"') + ']');
					} catch (e) {
						token.files = [];
					}
				} else {
					token.files = [];
				}
			}

			// turn the string expression into tokens.
			token.stack = Twig.expression.compile.apply(this, [{
				type:  Twig.expression.type.expression,
				value: expression
			}]).stack;

			// cleanup
			delete token.match;

			return token;
		}
944676
function replaceAssets(fileSrc) {
      //read page file data
      var htmlData = grunt.file.read(fileSrc);
      // console.log(htmlData)

      // var tsPrefix = 'auto_create_ts_com_';
      // var newTS = 'abc';
      // var testString = '"text/javascript" src="/js_build/app.auto_create_ts_com_1415079600.js"';
      // re1.test(testString);
      // testString.replace(re1, "$1" + newTS + "$3");

      var a1 = htmlData.match(re1)
      var num1 = !a1 ? 0 : a1.length
      console.log('Find ' + num1 + ' js ts string.')

      var a2 = htmlData.match(re2)
      var num2 = !a2 ? 0 : a2.length
      console.log('Find ' + num2 + ' css ts string.')

      if(num1 || num2) {

        var newdata = htmlData.replace(re1, "$1" + newTS + "$3");
        newdata = newdata.replace(re2, "$1" + newTS + "$3");

        if (grunt.file.write(fileSrc, newdata)) {
          grunt.log.success(fileSrc + ' replace ts successfully');
        } else {
          grunt.log.error(fileSrc + ' replace ts failed');
        }
      }
      else
        grunt.log.error('Can not find ts string in file: ' + fileSrc)

    }
1108869
function(src, regex, substr, options, index, actionName) {
    //takes the src content and changes the content
    var regExp = null,
        updatedSrc;
    if (typeof regex ===  'string') {
      regExp = new RegExp(regex , options); //regex => string
    } else {
      regExp = regex; //regex => RegExp object
    }
    updatedSrc = String(src).replace(regExp, substr); //note: substr can be a function
    index = typeof index === 'undefined' ? '' : index;
    if (!actionName) {
      grunt.log.verbose.ok(index + 1 + ' action(s) completed.');
    } else {
      grunt.log.verbose.ok(actionName + ' action completed.');
    }
    return updatedSrc;
  }
495540
function( string ) {
		return ( string || '' ).replace( ramp, "&amp;" )
			.replace( rquote, "&quot;" )
			.replace( rsquote, "&#039;" )
			.replace( rlt, "&lt;" )
			.replace( rgt, "&gt;" );
	}
319538
function replaceBadCharacters( text ) {
  var i, repl;
  for ( i = 0; i < rLen; i++ ) {
    repl = replacements[i];
    text = text.replace( repl[0], repl[1] );
  }
  return text;
}
1054604
function removeAccent(str) {
        var reAccents = /[àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ]/g;

        // Prefixed with some char to avoid off-by-one:
        var replacements = '_aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY';

        return str.replace(reAccents, function (match) {
            return replacements[reAccents.source.indexOf(match)];
        });
    }
952564
function replaceWithSpacer(style) {
    const lines = style.content.split('\n').length;
    const spacer = new Array(lines).join('\n');
    _.set(style, 'content', spacer);
}
233155
function urlMatch (asset, pattern) {
  var multi = pattern.split(',')
  var re

  if (multi.length > 1) {
    for (var i = 0, len = multi.length; i < len; i++) {
      re = new RegExp(multi[i].replace(/([.?+^$[\]\\(){}|/-])/g, '\\$1').replace(/\*/g, '.*'))
      if (re.test(asset)) {
        return true
      }
    }
    return false
  }

  re = new RegExp(pattern.replace(/([.?+^$[\]\\(){}|/-])/g, '\\$1').replace(/\*/g, '.*'))
  return re.test(asset)
}
1293689
def _replace_options(string, options)
      # Unescape the string so we can use the returned string
      # to set an elements inner html.
      s = string.gsub('&lt;', '<').gsub('&gt;', '>')

      if options
        # But escape option values to prevent code injection
        s.gsub(/%\{(\w+)\}/) do |m|
          key = ($1 || m.tr("%{}", ""))

          if options.key?(key)
            options[key].to_s.gsub('<', '&lt;').gsub('>', '&gt;')
          else
            key
          end
        end
      else
        s
      end
    end
807574
private String stringReplace(String text, String target, String replacement) {
		return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
				text).replaceAll(replacement);
	}
719657
function( replace ){
        var _buffer = [],
            _url,
            _code,
            _files  = replace.css ,
            _filename;
        for( var i = _files.length; i--; ){
            _url    = Path.join( config.dir.srcDir , _files[ i ] );
            if( grunt.file.exists( _url ) ){
                _code = tool.fixImageUrl( grunt.file.read( _url ).toString() , _url );
                _buffer.push( _code );
            };
        };
        _code = new mincss( config.mincss ).minify( _buffer.join( "" ) );
        _filename   = "css/" + MD5( _code ) + ".css";
        grunt.file.write( Path.join( config.dir.pubDir , _filename ) , _code );
        return _filename;
    }
746507
function replace(targetStr, searchStr, replaceStr, nPrev, nNext) {
  let result = targetStr;
  for (let i = 0; i < result.length; ++i) {
    if (result.substr(i, searchStr.length) === searchStr &&
      checkSubStr(result, i - nPrev.length, nPrev) === false &&
      checkSubStr(result, i + searchStr.length, nNext) === false) {
      result = result.slice(0, i) + replaceStr + result.slice(i + searchStr.length);
    }
  }
  return result;
}
360541
public void replace(String what, Object with) {
    if (what.charAt(0)=='$')
      throw new RuntimeException("$ is now control char that denotes URL encoding!");
    for (Placeholder p : _placeholders.get(what))
      p.end.insertAndAdvance(with.toString());

    for (Placeholder p : _placeholders.get("$"+what))
      try {
        p.end.insertAndAdvance(URLEncoder.encode(with.toString(),"UTF-8"));
      } catch (IOException e) {
        p.end.insertAndAdvance(e.toString());
      }
  }
1158875
function stringify (elements, options = {}) {
  const {
    embedAssets = true,
    assetPath = '',
    baseUrl = '',
    assetLoader = (filename) => fs.readFileAsync(filename, 'utf-8')
  } = options

  const [headWrappers, modifiers, assets] = extractTypes(elements, [HeadWrapper, PageModifier, Asset])

  const latestById = {}
  headWrappers.forEach(w => {
    if (w.options.id) {
      latestById[w.options.id] = w
    }
  })

  const bodyClassesMap = {}
  modifiers
    .filter(m => m.options.type === 'body-classed')
    .forEach(m => {
      bodyClassesMap[m.options.class] = m.options.classed
    })

  const bodyClass = Object.keys(bodyClassesMap)
    .filter(c => bodyClassesMap[c])
    .join(' ')

  const headElements = headWrappers
    .filter(w => w.options.id ? w === latestById[w.options.id] : true)
    .map(w => w.element)
    .map(e => e.stringify ? e.stringify() : (isString(e) ? e : ''))
    .join('')

  const bodyElements = elements
    .map(e => e !== undefined && e.stringify ? e.stringify() : (isString(e) ? e : ''))
    .join('')

  // only keep unique assets
  const uniqueAssetsMap = {}
  const anonymousAssets = []
  assets.forEach(asset => {
    if (asset.url) {
      uniqueAssetsMap[asset.url] = asset
    } else {
      anonymousAssets.push(asset)
    }
  })
  const uniqueAssets = Object.keys(uniqueAssetsMap).map(k => uniqueAssetsMap[k])

  const exportAssets = []

  const stylesheets = Promise.all(uniqueAssets.filter(a => a.url.endsWith('.css')).map(s => {
    if (embedAssets) {
      if (s.content) {
        return `<style>${s.content}</style>`
      } else {
        return assetLoader(s.filename)
          .then(content => `<style>${content}</style>`)
      }
    } else {
      exportAssets.push(s)
      return `<link rel="stylesheet" href="${path.join(baseUrl, assetPath, s.url)}"></link>`
    }
  }))

  const anonymousStylesheets = anonymousAssets.filter(a => a.type === 'css').map(s => {
    if (s.content) {
      return `<style>${s.content}</style>`
    } else {
      return assetLoader(s.filename)
        .then(content => `<style>${content}</style>`)
    }
  })

  const scripts = Promise.all(uniqueAssets.filter(a => a.url.endsWith('.js')).map(s => {
    if (embedAssets) {
      if (s.content) {
        return `<script>${s.content}</script>`
      } else {
        return assetLoader(s.filename)
          .then(content => `<script>${content}</script>`)
      }
    } else {
      exportAssets.push(s)
      return `<script src="${path.join(baseUrl, assetPath, s.url)}"></script>`
    }
  }))

  const anonymousScripts = anonymousAssets.filter(a => a.type === 'js').map(s => {
    if (s.content) {
      return `<script>${s.content}</script>`
    } else {
      return assetLoader(s.filename)
        .then(content => `<script>${content}</script>`)
    }
  })

  // Also export any un-embeddable assets
  uniqueAssets.forEach(asset => {
    if (!asset.url.endsWith('.js') && !asset.url.endsWith('.css')) {
      exportAssets.push(asset)
    }
  })

  return Promise.all([stylesheets, scripts])
    .spread((stylesheets, scripts) => {
      const bodyClasses = 'qm-body-font' + (bodyClass ? ' ' + bodyClass : '')
      const head = `<head>${stylesheets.join('')}${anonymousStylesheets.join('')}${headElements}</head>`
      const body = `<body class="${bodyClasses}">${bodyElements}${scripts.join('')}${anonymousScripts.join('')}</body>`
      const html = `<!DOCTYPE html>\n<html>\n${head}\n${body}</html>`
      return {
        html: html,
        assets: exportAssets
      }
    })
}