DEV Community

Saurabh Ranjan
Saurabh Ranjan

Posted on • Edited on

Scarily similar names in javaScript

1 substr and substring

String.prototype.substr(…) the method extracts a specified number of characters in a string, from a start index (avoided when possible).

   let str = 'commonSourceOfTruth';
   // str.length : 19 

substr MDN takes parameters as (from, ?length).

str.substr(1, 10);  // 'ommonSourc'

substring MDN takes parameters as (start, ?end(exclusive)).

str.substring(1, 10);  // 'ommonSour'

😠 if we start from 0 both behave the same.

str.substr(0, 10);  // 'commonSour'
str.substring(0, 10);  // 'commonSour'

Example : Remove first and last character from a given string ❓

str.substr(1, str.length-2) // ommonSourceOfTrut
str.substring(1, str.length-1) // ommonSourceOfTrut as substring takes indices

💥 Your turn now. Comment your output below.

str.substring(0, 2) // ?
str.substring(2, 0) // ?

2 array.splice() and arr.slice()

I found an amazing article on these similar methods, and the article covered all the required parts that one should know.So there is no need to write it again 😂

My favorite from the above article is:
Example: Remove/add a string and replace/add with the new string ❓

let content = ['post', 'tweet', 'video', 'talk']
content.splice(1, 0, 'dev', 'ten mile')
// content is ['post', 'dev', 'ten mile', 'tweet', 'video', 'talk']

let content = ['post', 'tweet', 'video', 'talk']
content.splice(1, 1, 'dev', 'ten mile')
// content is ["post", "dev", "ten mile", "video", "talk"]

and


let social = ['twitter', 'instagram', 'facebook', 'myspace']
let sliced = social.slice(1,3);
// content is ["instagram", "facebook"]

let social = ['twitter', 'instagram', 'facebook', 'myspace']
let spliced = social.splice(1,3);
// content is  ["instagram", "facebook", "myspace"]

3 .textContent and .innerHTML

// textContent
<div id="targetNode">This is <span>some </span> text</div>

let targetNodeEl = document.querySelector('#targetNode');
let targetNodeElText = targetNodeEl.textContent;

console.log(targetNodeElText) // This is some  text
  • textContent is not parsed as HTML.
  • as it's not parsed XSS can be prevented
// innerHTML
let targetNodeElHtml = targetNodeEl.innerHTML;
console.log(targetNodeElHtml) // This is <span>some </span> text
  • innerHTML is parsed.
  • it won't return hidden elements.

Top comments (0)