Skip to content

Commit 5ca19d4

Browse files
committed
feat: add utility to replace a substring before the first occurrence of a search string
1 parent 35622d7 commit 5ca19d4

File tree

15 files changed

+1274
-0
lines changed

15 files changed

+1274
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
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/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+
- If a search string is an empty string, the function returns the provided string unchanged.
67+
68+
</section>
69+
70+
<!-- /.notes -->
71+
72+
<!-- Package usage examples. -->
73+
74+
<section class="examples">
75+
76+
## Examples
77+
78+
<!-- eslint no-undef: "error" -->
79+
80+
```javascript
81+
var replaceBefore = require( '@stdlib/string/replace-before' );
82+
83+
var out = replaceBefore( 'beep boop', 'p', 'see' );
84+
// returns 'seep boop'
85+
86+
out = replaceBefore( 'Hello World!', 'xyz', 'foo' );
87+
// returns 'Hello World!'
88+
89+
out = replaceBefore( 'Hello World!', '', 'foo' );
90+
// returns 'Hello World!'
91+
92+
out = replaceBefore( '', 'xyz', 'foo');
93+
// returns ''
94+
```
95+
96+
</section>
97+
98+
<!-- /.examples -->
99+
100+
<!-- Section for describing a command-line interface. -->
101+
102+
* * *
103+
104+
<section class="cli">
105+
106+
## CLI
107+
108+
<!-- CLI usage documentation. -->
109+
110+
<section class="usage">
111+
112+
### Usage
113+
114+
```text
115+
Usage: replace-before [options] --search=<string> --replacement=<string> [<string>]
116+
117+
Options:
118+
119+
-h, --help Print this message.
120+
-V, --version Print the package version.
121+
--search string Search string.
122+
--replacement string Replacement string.
123+
--split sep Delimiter for stdin data. Default: '/\\r?\\n/'.
124+
```
125+
126+
</section>
127+
128+
<!-- /.usage -->
129+
130+
<!-- CLI usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
131+
132+
<section class="notes">
133+
134+
### Notes
135+
136+
- If the split separator is a [regular expression][mdn-regexp], ensure that the `split` option is either properly escaped or enclosed in quotes.
137+
138+
```bash
139+
# Not escaped...
140+
$ echo -n $'foo\nbar\nbaz' | replace-before --search a --replacement b --split /\r?\n/
141+
142+
# Escaped...
143+
$ echo -n $'foo\nbar\nbaz' | replace-before --search a --replacement b --split /\\r?\\n/
144+
```
145+
146+
- The implementation ignores trailing delimiters.
147+
148+
</section>
149+
150+
<!-- /.notes -->
151+
152+
<!-- CLI usage examples. -->
153+
154+
<section class="examples">
155+
156+
### Examples
157+
158+
```bash
159+
$ replace-before abcdefg --search d --replacement pqr
160+
pqrdefg
161+
```
162+
163+
To use as a [standard stream][standard-streams],
164+
165+
```bash
166+
$ echo -n $'beep\nboop' | replace-before --search p --replacement see
167+
seep
168+
seep
169+
```
170+
171+
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.
172+
173+
```bash
174+
$ echo -n 'beep\tboop' | replace-before --search p --replacement see --split '\t'
175+
seep
176+
seep
177+
```
178+
179+
</section>
180+
181+
<!-- /.examples -->
182+
183+
</section>
184+
185+
<!-- /.cli -->
186+
187+
<!-- 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. -->
188+
189+
<section class="references">
190+
191+
</section>
192+
193+
<!-- /.references -->
194+
195+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
196+
197+
<section class="related">
198+
199+
</section>
200+
201+
<!-- /.related -->
202+
203+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
204+
205+
<section class="links">
206+
207+
[standard-streams]: https://en.wikipedia.org/wiki/Standard_streams
208+
209+
[mdn-regexp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
210+
211+
</section>
212+
213+
<!-- /.links -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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 pkg = require( './../package.json' ).name;
26+
var replaceBefore = require( './../lib' );
27+
28+
29+
// MAIN //
30+
31+
bench( pkg, function benchmark( b ) {
32+
var values;
33+
var out;
34+
var str;
35+
var i;
36+
37+
str = 'To be, or not to be, that is the question.';
38+
values = [
39+
'foo',
40+
'bar',
41+
'beep',
42+
'boop'
43+
];
44+
45+
b.tic();
46+
for ( i = 0; i < b.iterations; i++ ) {
47+
out = replaceBefore( str, '.', values[ i%values.length ] );
48+
if ( typeof out !== 'string' ) {
49+
b.fail( 'should return a string' );
50+
}
51+
}
52+
b.toc();
53+
if ( !isString( out ) ) {
54+
b.fail( 'should return a string' );
55+
}
56+
b.pass( 'benchmark finished' );
57+
b.end();
58+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
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 replacement;
46+
var search;
47+
var split;
48+
var flags;
49+
var args;
50+
var cli;
51+
var str;
52+
53+
// Create a command-line interface:
54+
cli = new CLI({
55+
'pkg': require( './../package.json' ),
56+
'options': require( './../etc/cli_opts.json' ),
57+
'help': readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
58+
'encoding': 'utf8'
59+
})
60+
});
61+
62+
// Get any provided command-line options:
63+
flags = cli.flags();
64+
if ( flags.help || flags.version ) {
65+
return;
66+
}
67+
if ( flags.search ) {
68+
search = flags.search;
69+
} else {
70+
search = '';
71+
}
72+
if ( flags.replacement ) {
73+
replacement = flags.replacement;
74+
} else {
75+
replacement = '';
76+
}
77+
// Get any provided command-line arguments:
78+
args = cli.args();
79+
if ( args.length ) {
80+
str = args[ 0 ];
81+
} else {
82+
// Treat an empty value as an empty string:
83+
str = '';
84+
}
85+
// Check if we are receiving data from `stdin`...
86+
if ( !stdinStream.isTTY ) {
87+
if ( flags.split ) {
88+
if ( !isRegExpString( flags.split ) ) {
89+
flags.split = '/'+flags.split+'/';
90+
}
91+
split = reFromString( flags.split );
92+
} else {
93+
split = RE_EOL;
94+
}
95+
return stdin( onRead );
96+
}
97+
console.log( replaceBefore( str, search, replacement ) ); // eslint-disable-line no-console
98+
99+
/**
100+
* Callback invoked upon reading from `stdin`.
101+
*
102+
* @private
103+
* @param {(Error|null)} error - error object
104+
* @param {Buffer} data - data
105+
* @returns {void}
106+
*/
107+
function onRead( error, data ) {
108+
var lines;
109+
var i;
110+
if ( error ) {
111+
return cli.error( error );
112+
}
113+
lines = data.toString().split( split );
114+
115+
// Remove any trailing separators (e.g., trailing newline)...
116+
if ( lines[ lines.length-1 ] === '' ) {
117+
lines.pop();
118+
}
119+
for ( i = 0; i < lines.length; i++ ) {
120+
console.log( replaceBefore( lines[ i ], search, replacement ) ); // eslint-disable-line no-console
121+
}
122+
}
123+
}
124+
125+
main();

0 commit comments

Comments
 (0)