2018-05-28 01:39:03 +02:00
/ * *
* @ author n1474335 [ n1474335 @ gmail . com ]
* @ copyright Crown Copyright 2018
* @ license Apache - 2.0
* /
2019-07-09 13:23:59 +02:00
import Operation from "../Operation.mjs" ;
import Utils from "../Utils.mjs" ;
2018-08-23 22:41:57 +02:00
import XRegExp from "xregexp" ;
2018-05-28 01:39:03 +02:00
/ * *
* Find / Replace operation
* /
class FindReplace extends Operation {
/ * *
* FindReplace constructor
* /
constructor ( ) {
super ( ) ;
this . name = "Find / Replace" ;
this . module = "Regex" ;
2018-05-29 00:42:43 +02:00
this . description = "Replaces all occurrences of the first string with the second.<br><br>Includes support for regular expressions (regex), simple strings and extended strings (which support \\n, \\r, \\t, \\b, \\f and escaped hex bytes using \\x notation, e.g. \\x00 for a null byte)." ;
2018-08-21 20:07:13 +02:00
this . infoURL = "https://wikipedia.org/wiki/Regular_expression" ;
2018-05-28 01:39:03 +02:00
this . inputType = "string" ;
this . outputType = "string" ;
this . args = [
{
"name" : "Find" ,
"type" : "toggleString" ,
"value" : "" ,
"toggleValues" : [ "Regex" , "Extended (\\n, \\t, \\x...)" , "Simple string" ]
} ,
{
"name" : "Replace" ,
"type" : "binaryString" ,
"value" : ""
} ,
{
"name" : "Global match" ,
"type" : "boolean" ,
"value" : true
} ,
{
"name" : "Case insensitive" ,
"type" : "boolean" ,
"value" : false
} ,
{
"name" : "Multiline matching" ,
"type" : "boolean" ,
"value" : true
2018-08-23 22:41:57 +02:00
} ,
{
"name" : "Dot matches all" ,
"type" : "boolean" ,
"value" : false
2018-05-28 01:39:03 +02:00
}
] ;
}
/ * *
* @ param { string } input
* @ param { Object [ ] } args
* @ returns { string }
* /
run ( input , args ) {
2018-08-23 22:41:57 +02:00
const [ { option : type } , replace , g , i , m , s ] = args ;
2018-05-28 01:39:03 +02:00
let find = args [ 0 ] . string ,
modifiers = "" ;
if ( g ) modifiers += "g" ;
if ( i ) modifiers += "i" ;
if ( m ) modifiers += "m" ;
2018-08-23 22:41:57 +02:00
if ( s ) modifiers += "s" ;
2018-05-28 01:39:03 +02:00
if ( type === "Regex" ) {
2018-08-23 22:41:57 +02:00
find = new XRegExp ( find , modifiers ) ;
2018-05-28 01:39:03 +02:00
return input . replace ( find , replace ) ;
}
if ( type . indexOf ( "Extended" ) === 0 ) {
find = Utils . parseEscapedChars ( find ) ;
}
2018-08-23 22:41:57 +02:00
find = new XRegExp ( Utils . escapeRegex ( find ) , modifiers ) ;
2018-05-28 01:39:03 +02:00
return input . replace ( find , replace ) ;
}
}
export default FindReplace ;