The CreatorCon Call for Content is officially open! Get started here.

How to check if a string contains backslash

Nen
Tera Guru

Hi All,

 

Do you know how to check if a string contains backslash?

 

I have a flow action with a REST step and it's working fine but one call encountered an error because the parameter that I'm passing contains a backslash (sample value: abcd\efgh). I tried testing the action by adding another backslash and it ran successfully (sample value: abcd\\efgh).

 

I wanted to try and check the value of the string and if it has a backslash, I'll add another one before passing the value as parameter to the action. I'm only on the first part (which is to iterate through the characters). I've tried the below but nothing worked.

 

var testStr = "abcd\efgh";
for (var i = 0; i < testStr.length; i++) {
  gs.info(testStr.charAt(i));
}

 

var testStr = "abcd\efgh";
for (var i = 0; i < testStr.length; i++) {
  gs.info(testStr[i]);
}

 

var testStr = "abcd\efgh";
var testStrArr = testStr.split('');
for (var i = 0; i < testStrArr.length; i++) {
  gs.info(testStrArr[i]);
}

 

Only the characters a-h gets logged. It seems like the backslash is not being read at all. I don't know if I'm missing something here but if you have an idea, please let me know.

 

Regards,

Nen

6 REPLIES 6

Community Alums
Not applicable

Hi @Nen ,

Please try indexOf , something like below:

if(yourfieldValue.indexOf('\\') >= 0)

 

Thanks for the reply. Unfortunately, it doesn't work.

 

Nen_0-1719448299517.png

 

Mark Manders
Mega Patron

Check if this works:

function escapeBackslashes(inputString) {
    // Check if the string contains a single backslash
    if (inputString.includes("\\")) {
        // Replace single backslashes with double backslashes
        return inputString.replace(/\\/g, "\\\\");
    }
    return inputString;
}

// Example usage:
var originalString = "This is a test string with a backslash \\ in it.";
var escapedString = escapeBackslashes(originalString);

gs.info("Original string: " + originalString);
gs.info("Escaped string: " + escapedString);

Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark

Hi. Thanks for the reply. But unfortunately, it doesn't work on my case.

 

Nen_1-1719448403858.png