Now that you’ve clarified, here is how I’d craft the regex pattern.
$str = '<th>HotFixID</th>'
$TableName = 'HotFixes_HOSTNAME'
$pattern = '<th>(\S+)(?=<)'
$replacement = & {'<th onclick="sortTable(this.cellIndex,''{0}'')">$1<input type="text" onfocus="filterTable(this.parentElement.cellIndex,''{0}'')" class="filterInput" />' -f $args[0],'$1'} $TableName
For the replacement you invoke a scriptblock and pass in the table name. I chose args[0]
but you could also make a named Param()
. If you inspect $replacement
you should see
<th onclick="sortTable(this.cellIndex,'HotFixes_HOSTNAME')">$1<input type="text" onfocus="filterTable(this.parentElement.cellIndex,'HotFixes_HOSTNAME')" class="filterInput" />
With the table name and the regex match $1
embedded. Now when you do your replacement
$str -Replace $pattern, $replacement
Your end result should be the desired
<th onclick="sortTable(this.cellIndex,'HotFixes_HOSTNAME')">HotFixID<input type="text" onfocus="filterTable(this.parentElement.cellIndex,'HotFixes_HOSTNAME')" class="filterInput" /></th>
Now let’s take a second and consider could there ever be a space before or after the >Value<
such as > Value<
? If so, throw a couple of “ZERO or more” regex space patterns \s*
around it
$str = '<th>HotFixID</th>'
$TableName = 'HotFixes_HOSTNAME'
$pattern = '<th>\s*(\S+)\s*(?=<)'
$replacement = & {
Param($table)
'<th onclick="sortTable(this.cellIndex,''{0}'')">$1<input type="text" onfocus="filterTable(this.parentElement.cellIndex,''{0}'')" class="filterInput" />' -f $table,'$1'
} $TableName
$str -Replace $pattern, $replacement
And if you wanted to do it inline/in one line
$str -replace '<th>\s*(\S+)\s*(?=<)',(& {'<th onclick="sortTable(this.cellIndex,''{0}'')">$1<input type="text" onfocus="filterTable(this.parentElement.cellIndex,''{0}'')" class="filterInput" />' -f $args[0],'$1'} $TableName)
Edit
Actually it can be simpler.
$str -replace '<th>\s*(\S+)\s*(?=<)',('<th onclick="sortTable(this.cellIndex,''{0}'')">$1<input type="text" onfocus="filterTable(this.parentElement.cellIndex,''{0}'')" class="filterInput" />' -f $TableName,'$1')