1

I try to read a string char by char, and detect if there is any new line, and create an output if this is the case.

strText = "A;B;C" & vbcrlf & "D;E;F"
wscript.echo strText

For i=1 To Len(strText)

    charx = Mid(strText,i,1)

    if charx = "\n" then
        wscript.echo "OMG, NEW LINE DETECTED!!!"
    end if
Next 

I tried it by comparing the readed char with "\n", but this failed.

Mykola
  • 3,343
  • 6
  • 23
  • 39
Black
  • 18,150
  • 39
  • 158
  • 271

3 Answers3

3

Use InStr function as follows:

option explicit
'On Error Resume Next
On Error GoTo 0
Dim strText, strResult
strResult = Wscript.ScriptName
strText = "A;B;C" & vbcrlf & "D;E;F;vbCrLf"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText
strText = "A;B;C" & vbNewLine & "D;E;F;vbNewLine"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText
strText = "A;B;C" & vbCr & "D;E;F;vbCr"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText
strText = "A;B;C" & vbLf & "D;E;F;vbLf"
strResult = strResult & vbNewLine & String(20, "-") & vbNewLine & testCrLf( strText)  & strText

Wscript.Echo strResult
Wscript.Quit

Function testCrLf( sText)
  If InStr(1, sText, vbCrLf, vbBinaryCompare) Then
    testCrLf = "CrLf detected in "
  Else
    testCrLf = "CrLf not found in "
  End If
End Function

Output:

==>cscript D:\VB_scripts\SO\32411401.vbs
32411401.vbs
--------------------
CrLf detected in A;B;C
D;E;F;vbCrLf
--------------------
CrLf detected in A;B;C
D;E;F;vbNewLine
--------------------
D;E;F;vbCround in A;B;C
--------------------
CrLf not found in A;B;C
D;E;F;vbLf

==>
JosefZ
  • 28,460
  • 5
  • 44
  • 83
2
if charx = vbLf then
    wscript.echo "OMG, NEW LINE DETECTED!!!"
end if

In vbscript "\n" is a string with two characters, no a new line character

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Thank you, this worked. I also tried it with `vbCrLf` before, but this was not successfull. – Black Sep 05 '15 at 09:34
  • 2
    @EdwardBlack, It didn't work with `vbCrLf` because this constant is a two characters string, a carriage return followed by a line feed, but you are iterating the string extracting one character at a time, and one character string can not be equal to a two characters string. – MC ND Sep 05 '15 at 09:35
-1

The simple way to identify new line is using Environment.NewLine

lezhni
  • 292
  • 2
  • 12