不使用正则表达式删除两个字符之间的字符串 Javascript
Remove string between two characters using no regex Javascript
我正在尝试从通过输入文件上传的文本文件中删除一个句子。我需要删除“/”和“/”之间的所有句子,以便注释行基本上。还有所有单行注释,例如“//”,但我已经处理过了。为此,我不允许使用任何正则表达式或替换函数。有没有人可以帮助我?谢谢
class Inpute extends Component{
constructor(props){
super(props);
this.state = {
fileName: '',
fileContent: ''
};
}
handleFile = e =>{
const file = e.target.files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
this.setState({fileName: file.name, fileContent: reader.result});
if(reader.result.includes('//')){
var newText = reader.result
newText = newText
.split('\n')
.filter(x => !x.includes('\/\/'))
.join('\n')
this.setState({fileName: file.name, fileContent: newText})
}
}
reader.onerror = () =>{
console.log('File Error : ', reader.error)
}
}
按 /
拆分字符串。您需要删除的部分都在奇数索引中,因此将它们过滤掉并将此数组连接回字符串。
const string = 'asdasada a/kkkkkkkk/a sdad asda s/xxxxx/s dasd';
const arr = string.split('/').filter((_, index) => index%2 === 0);
console.log(arr.join(''));
更新
我已将示例更改为仅过滤评论
const line = 'asdasada a/*kkkkkkkk*/a sdad asda s/*xxxxxs dasd x asda sd\n' +
'asdas */das a// asdasda\n' +
'x/*bbbbb*/c ad';
let prevPart = null;
let haveDoubleSlashes = false;
const cleaned = line.split('/').map(part => {
// single line comments
if (haveDoubleSlashes || part === '') {
haveDoubleSlashes = true;
if (part.includes('\n')) {
part = '\n' + part.split('\n')[1];
haveDoubleSlashes = false;
} else {
part = null;
}
return part;
}
/* multiline comments */
if (part.startsWith('*') && part.endsWith('*')) {
prevPart = null;
return null;
}
if (prevPart !== null) {
part = '/' + part;
}
prevPart = part;
return part;
}).filter(part => part !== null).join('');
console.log(cleaned);
如果您只关心该行是否包含两个斜线字符 (/
),只需对其进行过滤:
const sample = `blah blah // blah blah\nblah blah /blah blah/ blah\nblah blah blah`;
const lines = sample.split('\n');
const good = lines.filter(x =>
// [...x] makes the line an array of characters
// reduce runs for each character, aggregating the result.
// agg is the aggregation, cur is the current character
// Here it's just counting the number of /s and returning false if there are
// fewer than two
[...x].reduce((agg, cur) => agg = cur === '/' ? agg + 1 : agg, 0) < 2
);
console.log(good.join('\n'));
function stripMultilineComments(str) {
let posOpen;
let posClose;
while ((posOpen = str.indexOf('/*')) !== -1) {
posClose = Math.max(
0, str.indexOf('*/', (posOpen + 2))
) || (str.length - 2);
str = [
str.substring(0, posOpen),
str.substring(posClose + 2),
].join('');
}
return str;
}
function stripSingleLineComment(str) {
let idx;
if (
(str.trim() !== '') &&
((idx = str.indexOf('//')) !== -1)
) {
str = str.substring(0, idx);
}
return str;
}
function stripComments(value) {
return stripMultilineComments(
String(value)
)
.split('\n')
.map(stripSingleLineComment)
.join('\n');
}
const sampleData = `
Lorem ipsum dolor sit amet/*, consectetur adipiscing elit,
sed do eiusmod tempor incididunt*/ ut labore et dolore
magna aliqua. // Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris/*nisi ut
aliquip //ex ea commodo consequat*/. Duis aute irure dolor
in reprehenderit// in voluptate velit esse cillum dolore
eu fugiat nulla pariatur.// Excepteur sint occaecat
/*cupidatat non //proident, */sunt in culpa qui officia
deserunt mollit anim id est laborum.
`;
console.log(
stripComments(sampleData)
);
console.log(
stripComments(sampleData) === `
Lorem ipsum dolor sit amet ut labore et dolore
magna aliqua.
quis nostrud exercitation ullamco laboris. Duis aute irure dolor
in reprehenderit
eu fugiat nulla pariatur.
sunt in culpa qui officia
deserunt mollit anim id est laborum.
`);
.as-console-wrapper { min-height: 100%!important; top: 0; }
我正在尝试从通过输入文件上传的文本文件中删除一个句子。我需要删除“/”和“/”之间的所有句子,以便注释行基本上。还有所有单行注释,例如“//”,但我已经处理过了。为此,我不允许使用任何正则表达式或替换函数。有没有人可以帮助我?谢谢
class Inpute extends Component{
constructor(props){
super(props);
this.state = {
fileName: '',
fileContent: ''
};
}
handleFile = e =>{
const file = e.target.files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
this.setState({fileName: file.name, fileContent: reader.result});
if(reader.result.includes('//')){
var newText = reader.result
newText = newText
.split('\n')
.filter(x => !x.includes('\/\/'))
.join('\n')
this.setState({fileName: file.name, fileContent: newText})
}
}
reader.onerror = () =>{
console.log('File Error : ', reader.error)
}
}
按 /
拆分字符串。您需要删除的部分都在奇数索引中,因此将它们过滤掉并将此数组连接回字符串。
const string = 'asdasada a/kkkkkkkk/a sdad asda s/xxxxx/s dasd';
const arr = string.split('/').filter((_, index) => index%2 === 0);
console.log(arr.join(''));
更新
我已将示例更改为仅过滤评论
const line = 'asdasada a/*kkkkkkkk*/a sdad asda s/*xxxxxs dasd x asda sd\n' +
'asdas */das a// asdasda\n' +
'x/*bbbbb*/c ad';
let prevPart = null;
let haveDoubleSlashes = false;
const cleaned = line.split('/').map(part => {
// single line comments
if (haveDoubleSlashes || part === '') {
haveDoubleSlashes = true;
if (part.includes('\n')) {
part = '\n' + part.split('\n')[1];
haveDoubleSlashes = false;
} else {
part = null;
}
return part;
}
/* multiline comments */
if (part.startsWith('*') && part.endsWith('*')) {
prevPart = null;
return null;
}
if (prevPart !== null) {
part = '/' + part;
}
prevPart = part;
return part;
}).filter(part => part !== null).join('');
console.log(cleaned);
如果您只关心该行是否包含两个斜线字符 (/
),只需对其进行过滤:
const sample = `blah blah // blah blah\nblah blah /blah blah/ blah\nblah blah blah`;
const lines = sample.split('\n');
const good = lines.filter(x =>
// [...x] makes the line an array of characters
// reduce runs for each character, aggregating the result.
// agg is the aggregation, cur is the current character
// Here it's just counting the number of /s and returning false if there are
// fewer than two
[...x].reduce((agg, cur) => agg = cur === '/' ? agg + 1 : agg, 0) < 2
);
console.log(good.join('\n'));
function stripMultilineComments(str) {
let posOpen;
let posClose;
while ((posOpen = str.indexOf('/*')) !== -1) {
posClose = Math.max(
0, str.indexOf('*/', (posOpen + 2))
) || (str.length - 2);
str = [
str.substring(0, posOpen),
str.substring(posClose + 2),
].join('');
}
return str;
}
function stripSingleLineComment(str) {
let idx;
if (
(str.trim() !== '') &&
((idx = str.indexOf('//')) !== -1)
) {
str = str.substring(0, idx);
}
return str;
}
function stripComments(value) {
return stripMultilineComments(
String(value)
)
.split('\n')
.map(stripSingleLineComment)
.join('\n');
}
const sampleData = `
Lorem ipsum dolor sit amet/*, consectetur adipiscing elit,
sed do eiusmod tempor incididunt*/ ut labore et dolore
magna aliqua. // Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris/*nisi ut
aliquip //ex ea commodo consequat*/. Duis aute irure dolor
in reprehenderit// in voluptate velit esse cillum dolore
eu fugiat nulla pariatur.// Excepteur sint occaecat
/*cupidatat non //proident, */sunt in culpa qui officia
deserunt mollit anim id est laborum.
`;
console.log(
stripComments(sampleData)
);
console.log(
stripComments(sampleData) === `
Lorem ipsum dolor sit amet ut labore et dolore
magna aliqua.
quis nostrud exercitation ullamco laboris. Duis aute irure dolor
in reprehenderit
eu fugiat nulla pariatur.
sunt in culpa qui officia
deserunt mollit anim id est laborum.
`);
.as-console-wrapper { min-height: 100%!important; top: 0; }