반응형

[javascript] 파라미터 제거하기. remove url parameters with javascript or jquery

 

https://stackoverflow.com/questions/4651990/remove-url-parameters-with-javascript-or-jquery

 

remove url parameters with javascript or jquery

I am trying to use the youtube data api to generate a video playlist. However, the video urls require a format of: youtube.com/watch?v=3sZOD3xKL0Y but what the api generates is: youtube.com/wa...

stackoverflow.com

var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';

url = url.slice( 0, url.indexOf('&') );

alert( url );

 

var url = document.createElement('a');
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';

console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(url.protocol); // https:
console.log(url.host); // developer.mozilla.org
console.log(url.hostname); // developer.mozilla.org
console.log(url.port); // (blank - https assumes port 443)
console.log(url.pathname); // /en-US/search
console.log(url.search); // ?q=URL
console.log(url.hash); // #search-results-close-container
console.log(url.origin); // https://developer.mozilla.org



window.location.replace(window.location.pathname)

https://jsfiddle.net/mill01/hxrejz5L/6/

 

반응형
반응형

A list of one-liners you should know to up your knowledge of JavaScript.

1.# Copy content to the clipboard

In order to improve the user experience of the website, we often need to copy the content to the clipboard, so that users can paste it to the designated place.

const copyToClipboard = (content) => navigator.clipboard.writeText(content)

copyToClipboard("Hello fatfish")

2.# Get the mouse selection

Have you encountered this kind of situation before?

We need to get the content selected by the user.

const getSelectedText = () => window.getSelection().toString()

getSelectedText()

3.# Shuffle an array

Shuffle an array? This is very common in lottery programs, but it’s not truly random.

const shuffleArray = array => array.sort(() => Math.random() - 0.5)

shuffleArray([ 1, 2,3,4, -1, 0 ]) // [3, 1, 0, 2, 4, -1]

4.# Convert rgba to hexadecimal

We can convert the rgba and hexadecimal color values to each other.

const rgbaToHex = (r, g, b) => "#" + [r, g, b].map(num => parseInt(num).toString(16).padStart(2, '0')).join('')

rgbaToHex(0, 0 ,0) // #000000
rgbaToHex(255, 0, 127) //#ff007f

5.# Convert hexadecimal to rgba

const hexToRgba = hex => {
  const [r, g, b] = hex.match(/\w\w/g).map(val => parseInt(val, 16))
  return `rgba(${r}, ${g}, ${b}, 1)`;
}

hexToRgba('#000000') // rgba(0, 0, 0, 1)
hexToRgba('#ff007f') // rgba(255, 0, 127, 1)

6.# Get the average of multiple numbers

Using reduce we can get the average value of a set of arrays very conveniently.

const average = (...args) => args.reduce((a, b) => a + b, 0) / args.length

average(0, 1, 2, -1, 9, 10) // 3.5

7.# Check if a number is even or odd

How can you tell if a number is odd or even?

const isEven = num => num % 2 === 0

isEven(2) // true
isEven(1) // false

8.# Deduplicate elements in an array

To remove duplicate elements in an array, using Set will make it very easy.

const uniqueArray = (arr) => [...new Set(arr)]

uniqueArray([ 1, 1, 2, 3, 4, 5, -1, 0 ]) // [1, 2, 3, 4, 5, -1, 0]

9.# Check if an object is an empty object

Is it easy to determine if an object is empty?

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

isEmpty({}) // true
isEmpty({ name: 'fatfish' }) // false

10.# Reverse a string

const reverseStr = str => str.split('').reverse().join('')

reverseStr('fatfish') // hsiftaf

11.# Calculate the interval between two dates

const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)

dayDiff(new Date("2023-06-23"), new Date("1997-05-31")) // 9519

12.# Find the day of the year in which the date falls

Today is June 23, 2023, so what day is it this year?

const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)

dayInYear(new Date('2023/06/23'))// 174

13.# Capitalize the first letter of the string

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("hello fatfish")  // Hello fatfish

14.# Generate a random string of specified length

const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')

generateRandomString(12) // cysw0gfljoyx
generateRandomString(12) // uoqaugnm8r4s

15.# Get a random integer between two integers

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

random(1, 100) // 27
random(1, 100) // 84
random(1, 100) // 55

16.# Specified digits rounded

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(3.1415926, 3) //3.142
round(3.1415926, 1) //3.1

17.# Clear all cookies

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`))

18.# Detect if it is dark mode

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)

19.# Scroll to the top of the page

const goToTop = () => window.scrollTo(0, 0)

goToTop()

20.# Determine if it is an Apple device

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform)

isAppleDevice()

21.# Random Boolean values

const randomBoolean = () => Math.random() >= 0.5

randomBoolean()

22.# Get the type of the variable

const typeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()

typeOf('')     // string
typeOf(0)      // number
typeOf()       // undefined
typeOf(null)   // null
typeOf({})     // object
typeOf([])     // array
typeOf(0)      // number
typeOf(() => {})  // function

23.# Determine if the current tab is active or not

const checkTabInView = () => !document.hidden

24.# Check if an element is focused

const isFocus = (ele) => ele === document.activeElement

25.# Random IP

const generateRandomIP = () => {
  return Array.from({length: 4}, () => Math.floor(Math.random() * 256)).join('.');
}

generateRandomIP() // 220.187.184.113
generateRandomIP() // 254.24.179.151

More content at PlainEnglish.io.

 

 

https://javascript.plainenglish.io/25-killer-javascript-one-liners-thatll-make-you-look-like-a-pro-d43f08529404

 

25 Killer JavaScript One-Liners That’ll Make You Look Like a Pro

A list of one-liners you should know to up your knowledge of JavaScript.

javascript.plainenglish.io

 

반응형
반응형

숫자에 콤마 제거

 

replace comma

금액필드에 , 제거 해야할 경우

 

amount.replace(",", "");

-> only replace one comma

-> 앞에 한개만 제거

 

amount.replace(/,/g, '');

-> replace all comma

-> 모든 콤마 제거

-> 정규식

 

How to replace all of comma

 

Result)

amount = "1,000,000"

 

amount.replace(",", "");

1000,000

 

amount.replace(/,/g, '');

1000000

반응형
반응형

== javascript 버전 ==

 

- textarea 의 줄바꿈 부분을 <br/>로 변경

 

var str = document.getElementById("textarea").value;

str = str.replace(/(?:\r\n|\r|\n)/g, '<br/>');

document.getElementById("textarea").value = str;

 

 

- <br/> 부분 줄바꿈 변경

 

var str = document.getElementById("textarea").value;

str = str.replaceAll("<br/>", "\r\n");

document.getElementById("textarea").value = str;

 

 

 

 

 

 

 

== jquery 버전 ==

 

- 줄바꿈 <br/>로 변경

 

var str = $('#textarea').val();

str = str.replace(/(?:\r\n|\r|\n)/g, '<br/>');

$('#textarea').val(str);

 

 

- <br/> 부분 줄바꿈 변경

 

var str = $('.#textarea').val();

str = str.split('<br/>').join("\r\n");

$('#textarea').val(str);

반응형
반응형

[javascript] 자바스크립트를 사용하여 현재 페이지를 새로고침, 갱신하지 않으면서 다른 주소로 변경하는 방법

 

History: pushState()

https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

 

History: pushState() method - Web APIs | MDN

In an HTML document, the history.pushState() method adds an entry to the browser's session history stack.

developer.mozilla.org

history.pushstate(state, title, url)

state = 상태 값을 나타내는 것으로 브라우저에서 앞/ 뒤로 갈 때, 넘겨줄 데이터

title = 변경할 브라우저 제목 (변경을 원하지 않으면 null

url = 변경할 브라우저 URL

 

const state = { page_id: 1, user_id: 5 };
const url = "hello-world.html";

history.pushState(state, "", url);



const url = new URL(location);
url.searchParams.set("foo", "bar");
history.pushState({}, "", url);

검색 페이지나 페이지네이션(pagination)을 가진 페이지에서 많이 사용됩니다. 즉 검색 조건이나 페이지 전환이 비동기식 ajax로 이루어질때 이를 반영하기 위해 페이지 주소를 함께 변경하는 것입니다. 페이지 주소를 변경해두면 만약 페이지를 리로드, 갱신하더라도 바뀐 주소나 쿼리 스트링 정보를 그대로 가져올 수 있기 때문이죠.

pushstate()의 장점은 페이지 주소만 변경하는 것이 아니라 url 주소를 바꾸면서 동시에 데이터(state)를 전달하거나 타이틀 변경도 가능하다는 점입니다.

  • 데이터 state 값 전달 가능
  • 페이지 타이틀 변경

 

window.onpopstate = function(event) {
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
}

브라우저에서 뒤/앞으로 가는 버튼 클릭 시 onpopstate 이벤트가 발생하며 이때, 콜백함수에서 event.state는 pushState 함수의 인자 값이였던 state 객체가 넘어온 것이다.

 

onhashchange를 이용할 수도 있다. 

반응형
반응형

 

scrollHeight 가져오기

<textarea id="ele">
  a
  bc
  def
  ghij
  klmno
</textarea>
<br>
<button onclick="getScHeight();">getScrollHeight</button>

getScHeight = function() {
  var scHeight = $('#ele').prop('scrollHeight');
  console.log(scHeight);
};
반응형
반응형

[jQuery]  URL에서 해시 값 가져오기

1. 모든 URL에 대한 해시 값 가져오기

순수한 JavaScript를 사용하면 주어진 값에서 해시 값을 얻을 수 있습니다. indexOf() 그리고 substring(), 아래에 설명된 대로:

var url = "https://mail.google.com/mail/u/0/#inbox";
var index = url.indexOf("#");
if (index !== -1)
{
    var hash = url.substring(index + 1);
    console.log(hash);
}
 

 
당신은 또한 사용할 수 있습니다 split() 방법 pop() 방법은 아래와 같습니다.

var url = "https://mail.google.com/mail/u/0/#inbox";
var parts = url.split('#');
if (parts.length > 1) {
    console.log(parts.pop());
}
 

2. 현재 URL의 해시 값 가져오기

또는 현재 창 URL에 대한 해시 값이 필요한 경우 다음을 사용할 수 있습니다. window.location.hash, 다음을 포함하는 문자열을 반환합니다. '#', URL의 조각 식별자가 뒤따릅니다. URL에 조각 식별자가 없으면 빈 문자열을 반환합니다. "".

// 'https://www.techiedelight.com/#input'에 대해 '#input'을 반환합니다.
var hash = window.location.hash;
 

 
jQuery를 사용하면 다음을 사용할 수 있습니다. .prop()  location 해시를 얻기 위한 객체:

// 'https://www.techiedelight.com/#input'에 대해 '#input' 반환
var hash = $(location).prop('hash');
 

 
URL의 조각 식별자만 추출하려면 '#', 당신은 사용할 수 있습니다 substr() 다음과 같은 방법:

// 'https://www.techiedelight.com/#input'에 대한 'input'을 반환합니다.

// JavaScript로
var hash = window.location.hash.substr(1);

// jQuery로
var hash = $(location).prop('hash').substr(1);
 

 
다음은 다음을 사용하는 또 다른 솔루션입니다. window.location.href.

// 'https://www.techiedelight.com/#input'에 대한 'input'을 반환합니다.
window.location.href.split('#').pop();​
반응형
반응형

With the rapidly changing technologies, developers are being provided with incredible new tools and APIs. But it has been seen that out of the 100+ APIs, only 5% of them are actively used by developers.

Let’s take a look at some of the useful Web APIs that can help you skyrocket your website to the moon! 🌕🚀

1. Screen Capture API

The Screen Capture API, as the name suggests, allows you to capture the contents of a screen, making the process of building a screen recorder a piece of cake.

You need a video element to display the captured screen. The start button will start the screen capture.

<video id="preview" autoplay>
  Your browser doesn't support HTML5.
</video>
<button id="start" class="btn">Start</button>
const previewElem = document.getElementById("preview");
const startBtn = document.getElementById("start");

async function startRecording() {
  previewElem.srcObject =
    await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: true,
    });
}
startBtn.addEventListener("click", startRecording);

2. Web Share API

The Web Share API allows you to share text, links, and even files from a web page to other apps installed on the device.

async function shareHandler() {
  navigator.share({
    title: "Tapajyoti Bose | Portfolio",
    text: "Check out my website",
    url: "https://tapajyoti-bose.vercel.app/",
  });
}

NOTE: To use the Web Share API, you need an interaction from the user. For example, a button click or a touch event.

3. Intersection Observer API

The Intersection Observer API allows you to detect when an element enters or leaves the viewport. This is exceptionally useful for implementing infinite scroll.

 

NOTE: The demo uses React because of my personal preference, but you can use any framework or vanilla JavaScript.

4. Clipboard API

The Clipboard API allows you to read and write data to the clipboard. This is useful for implementing the copy to clipboard functionality.

async function copyHandler() {
  const text = "https://tapajyoti-bose.vercel.app/";
  navigator.clipboard.writeText(text);
}

5. Screen Wake Lock API

Ever wondered how YouTube prevents the screen from being switched off while playing the video? Well, that’s because of the Screen Wake Lock API.

let wakeLock = null;

async function lockHandler() {
  wakeLock = await navigator.wakeLock.request("screen");
}

async function releaseHandler() {
  await wakeLock.release();
  wakeLock = null;
}j

NOTE: You can only use the Screen Wake Lock API if the page is already visible on the screen. Otherwise, it would throw an error.

6. Screen Orientation API

The Screen Orientation API allows you to check the current orientation of the screen and even lock it to a specific orientation.

async function lockHandler() {
  await screen.orientation.lock("portrait");
}

function releaseHandler() {
  screen.orientation.unlock();
}

function getOrientation() {
  return screen.orientation.type;
}

7. Fullscreen API

The Fullscreen API allows you to display an element or the entire page in full screen.

async function enterFullscreen() {
  await document.documentElement.requestFullscreen();
}

async function exitFullscreen() {
  await document.exitFullscreen();
}

NOTE: To use the Fullscreen API too, you need an interaction from the user.

 

 

https://tapajyoti-bose.medium.com/7-javascript-web-apis-to-build-futuristic-websites-you-didnt-know-12b737ccf594

반응형

+ Recent posts