简体   繁体   中英

Compare a string to escape characters

Is there a way to compare a string against a string containing escape characters.

What I have to far is:

var text = '\\SPX\FTP';
if(text.substring(0,2) === '\\'){
    console.info('true')
}

This should be true but isn't.

As one of the \\ is escaped, you need to compare to one character only:

var text = '\\SPX\FTP';
if(text.substring(0,1) === '\\'){
    console.info('true')
}

If you have access to tagged template strings in ES6, or are transpiling using Babel, you can use String.raw :

var text = String.raw`\\SPX\FTP`;
if(text.substring(0,2) === String.raw`\\`){
    console.info('true')
}

Returns true .

Either compare to one character or two, depending on what you require.

One (I suspect this is the one you'll need):

var text = '\\SPX\FTP';
if (text.substring(0, 1) === '\\') { // Remember \\ after escape == \
    console.info('true')
}

Two:

var text = '\\SPX\FTP';
if (text.substring(0, 2) === '\\S') {
    console.info('true')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM