Skip to content

Commit ae68d17

Browse files
HarshitaKalanikgrytePranavchiku
authored
feat: add support for replacing the substring before the first occurrence of a search string
PR-URL: #843 Closes: #811 Co-authored-by: Athan Reines <kgryte@gmail.com> Co-authored-by: Pranav <85227306+Pranavchiku@users.noreply.github.com> Reviewed-by: Athan Reines <kgryte@gmail.com> Reviewed-by: Philipp Burckhardt <pburckhardt@outlook.com>
1 parent 23c8c4f commit ae68d17

File tree

15 files changed

+1290
-0
lines changed

15 files changed

+1290
-0
lines changed
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2023 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# replaceBefore
22+
23+
> Replace the substring before the first occurrence of a specified search string.
24+
25+
<!-- Section to include introductory text. Make sure to keep an empty line after the intro `section` element and another before the `/section` close. -->
26+
27+
<section class="intro">
28+
29+
</section>
30+
31+
<!-- /.intro -->
32+
33+
<!-- Package usage documentation. -->
34+
35+
<section class="usage">
36+
37+
## Usage
38+
39+
```javascript
40+
var replaceBefore = require( '@stdlib/string/base/replace-before' );
41+
```
42+
43+
#### replaceBefore( str, search, replacement )
44+
45+
Replaces the substring before the first occurrence of a specified search string.
46+
47+
```javascript
48+
var out = replaceBefore( 'beep boop', ' ', 'loop' );
49+
// returns 'loop boop'
50+
51+
out = replaceBefore( 'beep boop', 'o', 'bar' );
52+
// returns 'baroop'
53+
```
54+
55+
</section>
56+
57+
<!-- /.usage -->
58+
59+
<!-- Package usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
60+
61+
<section class="notes">
62+
63+
## Notes
64+
65+
- If a search string is not present in a provided string, the function returns the provided string unchanged.
66+
67+
</section>
68+
69+
<!-- /.notes -->
70+
71+
<!-- Package usage examples. -->
72+
73+
<section class="examples">
74+
75+
## Examples
76+
77+
<!-- eslint no-undef: "error" -->
78+
79+
```javascript
80+
var replaceBefore = require( '@stdlib/string/base/replace-before' );
81+
82+
var out = replaceBefore( 'beep boop', 'p', 'see' );
83+
// returns 'seep boop'
84+
85+
out = replaceBefore( 'Hello World!', 'xyz', 'foo' );
86+
// returns 'Hello World!'
87+
88+
out = replaceBefore( 'Hello World!', '', 'foo' );
89+
// returns 'Hello World!'
90+
91+
out = replaceBefore( '', 'xyz', 'foo');
92+
// returns ''
93+
```
94+
95+
</section>
96+
97+
<!-- /.examples -->
98+
99+
<!-- Section for describing a command-line interface. -->
100+
101+
* * *
102+
103+
<section class="cli">
104+
105+
## CLI
106+
107+
<!-- CLI usage documentation. -->
108+
109+
<section class="usage">
110+
111+
### Usage
112+
113+
```text
114+
Usage: replace-before [options] --search=<string> --replacement=<string> [<string>]
115+
116+
Options:
117+
118+
-h, --help Print this message.
119+
-V, --version Print the package version.
120+
--search string Search string.
121+
--replacement string Replacement string.
122+
--split sep Delimiter for stdin data. Default: '/\\r?\\n/'.
123+
```
124+
125+
</section>
126+
127+
<!-- /.usage -->
128+
129+
<!-- CLI usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
130+
131+
<section class="notes">
132+
133+
### Notes
134+
135+
- If the split separator is a [regular expression][mdn-regexp], ensure that the `split` option is either properly escaped or enclosed in quotes.
136+
137+
```bash
138+
# Not escaped...
139+
$ echo -n $'foo\nbar\nbaz' | replace-before --search a --replacement b --split /\r?\n/
140+
141+
# Escaped...
142+
$ echo -n $'foo\nbar\nbaz' | replace-before --search a --replacement b --split /\\r?\\n/
143+
```
144+
145+
- The implementation ignores trailing delimiters.
146+
147+
</section>
148+
149+
<!-- /.notes -->
150+
151+
<!-- CLI usage examples. -->
152+
153+
<section class="examples">
154+
155+
### Examples
156+
157+
```bash
158+
$ replace-before abcdefg --search d --replacement pqr
159+
pqrdefg
160+
```
161+
162+
To use as a [standard stream][standard-streams],
163+
164+
```bash
165+
$ echo -n $'beep\nboop' | replace-before --search p --replacement see
166+
seep
167+
seep
168+
```
169+
170+
By default, when used as a [standard stream][standard-streams], the implementation assumes newline-delimited data. To specify an alternative delimiter, set the `split` option.
171+
172+
```bash
173+
$ echo -n 'beep\tboop' | replace-before --search p --replacement see --split '\t'
174+
seep
175+
seep
176+
```
177+
178+
</section>
179+
180+
<!-- /.examples -->
181+
182+
</section>
183+
184+
<!-- /.cli -->
185+
186+
<!-- Section to include cited references. If references are included, add a horizontal rule *before* the section. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
187+
188+
<section class="references">
189+
190+
</section>
191+
192+
<!-- /.references -->
193+
194+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
195+
196+
<section class="related">
197+
198+
</section>
199+
200+
<!-- /.related -->
201+
202+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
203+
204+
<section class="links">
205+
206+
[standard-streams]: https://en.wikipedia.org/wiki/Standard_streams
207+
208+
[mdn-regexp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
209+
210+
</section>
211+
212+
<!-- /.links -->
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2023 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// MODULES //
22+
23+
var bench = require( '@stdlib/bench' );
24+
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
25+
var fromCodePoint = require( '@stdlib/string/from-code-point' );
26+
var pkg = require( './../package.json' ).name;
27+
var replaceBefore = require( './../lib' );
28+
29+
30+
// MAIN //
31+
32+
bench( pkg, function benchmark( b ) {
33+
var replacement;
34+
var out;
35+
var str;
36+
var i;
37+
38+
str = 'To be, or not to be, that is the question.';
39+
replacement = 'foo';
40+
41+
b.tic();
42+
for ( i = 0; i < b.iterations; i++ ) {
43+
out = replaceBefore( str, fromCodePoint( i%126 ), replacement );
44+
if ( typeof out !== 'string' ) {
45+
b.fail( 'should return a string' );
46+
}
47+
}
48+
b.toc();
49+
if ( !isString( out ) ) {
50+
b.fail( 'should return a string' );
51+
}
52+
b.pass( 'benchmark finished' );
53+
b.end();
54+
});
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
#!/usr/bin/env node
2+
3+
/**
4+
* @license Apache-2.0
5+
*
6+
* Copyright (c) 2023 The Stdlib Authors.
7+
*
8+
* Licensed under the Apache License, Version 2.0 (the "License");
9+
* you may not use this file except in compliance with the License.
10+
* You may obtain a copy of the License at
11+
*
12+
* http://www.apache.org/licenses/LICENSE-2.0
13+
*
14+
* Unless required by applicable law or agreed to in writing, software
15+
* distributed under the License is distributed on an "AS IS" BASIS,
16+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17+
* See the License for the specific language governing permissions and
18+
* limitations under the License.
19+
*/
20+
21+
'use strict';
22+
23+
// MODULES //
24+
25+
var resolve = require( 'path' ).resolve;
26+
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
27+
var CLI = require( '@stdlib/cli/ctor' );
28+
var stdin = require( '@stdlib/process/read-stdin' );
29+
var stdinStream = require( '@stdlib/streams/node/stdin' );
30+
var RE_EOL = require( '@stdlib/regexp/eol' ).REGEXP;
31+
var isRegExpString = require( '@stdlib/assert/is-regexp-string' );
32+
var reFromString = require( '@stdlib/utils/regexp-from-string' );
33+
var replaceBefore = require( './../lib' );
34+
35+
36+
// MAIN //
37+
38+
/**
39+
* Main execution sequence.
40+
*
41+
* @private
42+
* @returns {void}
43+
*/
44+
function main() {
45+
var split;
46+
var flags;
47+
var args;
48+
var cli;
49+
var str;
50+
51+
// Create a command-line interface:
52+
cli = new CLI({
53+
'pkg': require( './../package.json' ),
54+
'options': require( './../etc/cli_opts.json' ),
55+
'help': readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
56+
'encoding': 'utf8'
57+
})
58+
});
59+
60+
// Get any provided command-line options:
61+
flags = cli.flags();
62+
if ( flags.help || flags.version ) {
63+
return;
64+
}
65+
66+
// Get any provided command-line arguments:
67+
args = cli.args();
68+
69+
if ( args.length ) {
70+
str = args[ 0 ];
71+
} else {
72+
// Treat an empty value as an empty string:
73+
str = '';
74+
}
75+
// Check if we are receiving data from `stdin`...
76+
if ( !stdinStream.isTTY ) {
77+
if ( flags.split ) {
78+
if ( !isRegExpString( flags.split ) ) {
79+
flags.split = '/'+flags.split+'/';
80+
}
81+
split = reFromString( flags.split );
82+
} else {
83+
split = RE_EOL;
84+
}
85+
return stdin( onRead );
86+
}
87+
console.log( replaceBefore( str, flags.search || '', flags.replacement || '' ) );
88+
89+
/**
90+
* Callback invoked upon reading from `stdin`.
91+
*
92+
* @private
93+
* @param {(Error|null)} error - error object
94+
* @param {Buffer} data - data
95+
* @returns {void}
96+
*/
97+
function onRead( error, data ) {
98+
var lines;
99+
var i;
100+
if ( error ) {
101+
return cli.error( error );
102+
}
103+
lines = data.toString().split( split );
104+
105+
// Remove any trailing separators (e.g., trailing newline)...
106+
if ( lines[ lines.length-1 ] === '' ) {
107+
lines.pop();
108+
}
109+
for ( i = 0; i < lines.length; i++ ) {
110+
console.log( replaceBefore( lines[ i ], flags.search || '', flags.replacement || '' ) ); // eslint-disable-line max-len
111+
}
112+
}
113+
}
114+
115+
main();

0 commit comments

Comments
 (0)