0

I want to replace

$fieldTool.GetFieldValue($i
    tem,"Title")

with

{{(sc_get_field_value i_item 'Title')}}

The original string has a line break and I am using 'n like this $fieldTool.GetFieldValue($i'ntem,"Title")

This is the code

  $template = '<div class="tile-inspiration__title field-title">$fieldTool.GetFieldValue($i
  tem,"Title")</div>'
  $matchString = '$fieldTool.GetFieldValue($i'ntem,"Title")'
  $pattern = $([regex]::escape($matchString))
  $replaceString = "{{(sc_get_field_value i_item 'Title')}}"
  $newtemplate = $template -replace $pattern, $replaceString
  Write-Host $newtemplate

The above code is not working. How can I replace the string with line break with another string.

Any suggestion would be appreciated.

Thanks in advance

2
  • 2
    I don't know if it's just here because of the formatting but instead of a single quote 'n you should use a backtick for your linebreak pattern `n Commented Apr 7, 2022 at 7:48
  • @Theo that's not necessary, on input output it'll be automatically replaced by Environment.NewLine Commented Apr 7, 2022 at 11:32

1 Answer 1

1

To replace newlines, you should use regex pattern \r?\n. This will match both *nix as well as Windows newlines.

In your template string however, there are multiple characters that have special meaning in regex, therefore you need to do [regex]::Escape(), but that also would wrongfully escape the characters \r?\n, rendering it as \\r\?\\n, so adding that in the $matchString before escaping it, would be of no use.

You can manually first replace the newline with a character that otherwise is not present in the $matchString and has no special meaning in regex.

$template = '<div class="tile-inspiration__title field-title">$fieldTool.GetFieldValue($i
tem,"Title")</div>'
# for demo, I chose to replace the newline with an underscore
$matchString = '$fieldTool.GetFieldValue($i_tem,"Title")'
# now, escape the string and after that replace the underscore by the wanted \r?\n pattern
$pattern = [regex]::escape($matchString) -replace '_', '\r?\n'
# $pattern is now: \$fieldTool\.GetFieldValue\(\$i\r?\ntem,"Title"\)
$replaceString = "{{(sc_get_field_value i_item 'Title')}}"

# this time, the replacement should work
$newtemplate = $template -replace $pattern, $replaceString
Write-Host $newtemplate  # --> <div class="tile-inspiration__title field-title">{{(sc_get_field_value i_item 'Title')}}</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.