admin管理员组

文章数量:1291187

In this program, I understand (I think) that paragraph.charAT(0) = "%" checks whether the first character in paragraph is equal to %, i.e. the counting starts at 0, so charAT(0) is the first character

However, in the line, paragraph.slice(1), what does the 1 refer to? Is it slicing off the first character?, which in this case will be at 0 position?

function processParagraph(paragraph) {
  var header = 0;
  while (paragraph.charAt(0) == "%") {
    paragraph = paragraph.slice(1);
    header++;
  }

  return {type: (header == 0 ? "p" : "h" + header),
          content: paragraph};
}

show(processParagraph(paragraphs[0]));

In this program, I understand (I think) that paragraph.charAT(0) = "%" checks whether the first character in paragraph is equal to %, i.e. the counting starts at 0, so charAT(0) is the first character

However, in the line, paragraph.slice(1), what does the 1 refer to? Is it slicing off the first character?, which in this case will be at 0 position?

function processParagraph(paragraph) {
  var header = 0;
  while (paragraph.charAt(0) == "%") {
    paragraph = paragraph.slice(1);
    header++;
  }

  return {type: (header == 0 ? "p" : "h" + header),
          content: paragraph};
}

show(processParagraph(paragraphs[0]));
Share Improve this question asked Feb 25, 2011 at 3:02 mjmitchemjmitche 2,0676 gold badges25 silver badges31 bronze badges 2
  • 1 see here. MDC is a great resource for javascript. – aaronasterling Commented Feb 25, 2011 at 3:07
  • See also What is the difference between String.slice and String.substring in JavaScript? – Rudu Commented Feb 25, 2011 at 3:14
Add a ment  | 

4 Answers 4

Reset to default 9

It extracts a substring starting at index 1 (2nd character) of the paragraph string.

For example, consider this:

var paragraph = "Hi my name is Russell";
console.log( paragraph.slice(1) ); //returns 'i my name is Russell'

.slice

string.slice(beginslice[, endSlice])

Extracts a section of a string and returns a new string.

It returns everything after the first character, essentially cutting the first character off.

It removes the first character from the string and returns that without altering the original string. I remend you look at the documentation for slice.

it's slicing off the first character (which is a "%")

本文标签: javascriptwhat does the 1 in slice(1) refer to in this programStack Overflow