Skip to content

Instantly share code, notes, and snippets.

@sshongru
Last active August 29, 2015 14:02
Show Gist options
  • Save sshongru/b0e621d580ed5fb7686f to your computer and use it in GitHub Desktop.
Save sshongru/b0e621d580ed5fb7686f to your computer and use it in GitHub Desktop.
HTML String replace that maintains the original whitespace indentation of the token in the template.
/*
* This function replaces the token string with the replacement string, but maintains
* the original whitespace indentation the token had within the template.
*
* For example if your template has:
*
* <div>
* {% TOKEN %}
* </div>
*
* Then the output would be:
*
* <div>
* Hello
* World
* </div>
*
*/
replaceMaintainingTokenIndentation: function( string, token, replacement ){
// just quickly remove the token if there is nothing to replace it with
if ( replacement === undefined || replacement == '' ){
return string.replace( new RegExp( token, 'g' ), '' );
}
var index = string.indexOf( token ) - 1;
// replace each occurrence of the token
while ( index >= 0 ){
var indent = '';
// collect the whitespace between the token and the previous non-whitespace character
for ( index; index >= 0; index-- ){
var character = string.charAt( index );
// stop if we encounter non-whitespace
if ( character != ' ' && character != '\t' )
break;
indent += character;
}
// indent all but the first line of the replacement string
var newReplacement = replacement.replace( /\n/g, '\n' + indent );
// replace this occurrence of token with the properly indented replacement
string = string.replace( token, newReplacement );
// move on to the next occurence of the token
index = string.indexOf( token ) - 1;
}
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment