반응형
반응형

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

반응형
반응형

[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를 이용할 수도 있다. 

반응형

+ Recent posts