반응형
반응형

History API (https://developer.mozilla.org/ko/docs/Web/API/History_API)

DOM의 Window 객체는 history 객체를 통해 브라우저의 세션 기록에 접근할 수 있는 방법을 제공합니다. history는 사용자를 자신의 방문 기록 앞과 뒤로 보내고 기록 스택의 콘텐츠도 조작할 수 있는, 유용한 메서드와 속성을 가집니다.

 

History.pushState  페이지 이동 없이 주소만 바꿔준다. (브라우저의 뒤로가가 버튼이 활성화 된다.)

브라우저 페이지를 이동하게 되면 window.onpopstate 라는 이벤트가 발생하게 되는데, pushState  했을때는 popstate 이벤트가 발생하지않고,  / 앞으로 가기를 클릭 했을때 popstate 이벤트가 발생하게 된다.

즉, pushState 와 popstate 둘을 이용하여 SPA 의 페이지 전환을 구현할 수 있다.

 

기본 형태 - history.pushState(state, title, url);

State : 브라우저 이동  넘겨줄 데이터 (popstate 에서 받아서 원하는 처리를 해줄  있음)

Title : 변경할 브라우저 제목 (변경 원치 않으면 null)

Url : 변경할 주소

 

사용예)

window.onpopstate = function(e) { 
    console.log(`${JSON.stringify(e.state)} | ${location.origin} | ${location.pathname}`);
}

var state = {page_id : 1, data : 'test'};
var url = location.origin + '/myPage';
history.pushState(state, null, url);

 코드를 실행하면 history.pushState  수행했을때 브라우저 주소에 /myPage  붙는걸   있고,

뒤로가기를(원래 url) 한뒤 다시 앞으로(pushState 추가된 url) 가기를 클릭 하면

콘솔 출력값으로 {"page_id":1,"data":"test"} | http://localhost:5000 | /myPage  출력된다.

 

 

* https://kwangsunny.tistory.com/28

반응형
반응형

[javascript] 새로고침 없이 파라미터 제거/수정

 

Remove URL parameters without refreshing page

window.history.pushState({}, document.title, "/" + myNewURL );

https://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page

 

Remove URL parameters without refreshing page

I am trying to remove everything after the "?" in the browser url on document ready. Here is what I am trying: jQuery(document).ready(function($) { var url = window.location.href; url = url...

stackoverflow.com

 

1- The pushState() method if you want to add a new modified URL to history entries.

2- The replaceState() method if you want to update/replace current history entry.

.replaceState() operates exactly like .pushState() except that .replaceState()

 

For one liner fans, try this out in your console/firebug and this page URL will change:

window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);

This page URL will change from:

http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103

To

http://stackoverflow.com/22753103#22753103

 

History: pushState() method
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.replaceState() https://developer.mozilla.org/ko/docs/Web/API/History/replaceState

 

History.replaceState() - Web API | MDN

History.replaceState() 메서드는 현재 history를 수정해 메소드의 매개 변수에 전달 된 stateObj, title, URL로 대체합니다. 이 방법은 특히 일부 유저의 동작에 대한 응답으로 history 객체의 상태나 현재 history

developer.mozilla.org

 

반응형
반응형

[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);

반응형

+ Recent posts