Resizing and cropping images using the Canvas element. Resizing and cropping images with the Canvas element Resizing from different angles

If (!String.prototype.trim) ( (function() ( // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/ g; String.prototype.trim = function() ( return this.replace(rtrim, ""); ); ))(); )

See it:

String.prototype.trim=function()(return this.replace(/^\s+|\s+$/g, "");); String.prototype.ltrim=function()(return this.replace(/^\s+/,"");); String.prototype.rtrim=function()(return this.replace(/\s+$/,"");); String.prototype.fulltrim=function()(return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace( /\s+/g," "););


479

Chromium: 5+

opera: 10.5+


126

It's not surprising that regular expression based slower than the traditional cycle.

Here is my personal example. This code is very old! I wrote it for JavaScript1.1 and Netscape 3 and it has only been slightly updated since then. (Original used String.charAt)

/** * Trim string. actually trims all control characters. * Ignores fancy Unicode spaces. Forces to string. */ function trim(str) ( str = str.toString(); var begin = 0; var end = str.length - 1; while (begin<= end && str.charCodeAt(begin) < 33) { ++begin; } while (end >begin && str.charCodeAt(end)< 33) { --end; } return str.substr(begin, end - begin + 1); }


13

Use your own JavaScript methods: String.trimLeft() , String.trimRight() and String.trim() .

String.trim() is supported in IE9+ and all other major browsers:

" Hello ".trim() //-> "Hello"

String.trimLeft() and String.trimRight() are non-standard but are supported in all major browsers, except IE

" Hello ".trimLeft() //-> "Hello " " Hello ".trimRight() //-> " Hello"

IE support is easy with a polyfill however:

If (!"".trimLeft) ( String.prototype.trimLeft = function() ( return this.replace(/^\s+/,""); ); String.prototype.trimRight = function() ( return this.replace (/\s+$/,""); ); if (!"".trim) ( String.prototype.trim = function() ( return this.replace(/^\s+|\s+$/g, "" ); ); ) )


10

String.prototype.trim = String.prototype.trim || function () ( return this.replace(/^\s+|\s+$/g, ""); ); String.prototype.trimLeft = String.prototype.trimLeft || function () ( return this.replace(/^\s+/, ""); ); String.prototype.trimRight = String.prototype.trimRight || function () ( return this.replace(/\s+$/, ""); ); String.prototype.trimFull = String.prototype.trimFull || function () ( return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, ""); );


7

Var trim = (function() ( // if a reference is a `String`. function isString(value)( return typeof value == "string"; } // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn"t have it... :-(// TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function(value) { return isString(value) ? value.replace(/^\s*/, "").replace(/\s*$/, "") : value; }; } return function(value) { return isString(value) ? value.trim() : value; }; })(); !}

and call it like trim(" hello ")


4

use simple code

varstr = "Hello World!"; alert(str.trim());

Browser Support

FeatureChromeFirefox Internet Explorer Opera Safari Edge Basic support (Yes) 3.5 9 10.5 5 ?

For an old browser, add a prototype


4

Here is a very simple way:

Function removeSpaces(string)( return string.split(" ").join(""); )


3

You can simply declare a variable as a string and use its trim function:

var str = new String("my string"); str= str.trim();


2

Today, almost every browser supports String.prototype.trim() .

You use it like this:

origStr = "foo"; var newStr = origStr.trim(); // Value of newStr becomes "foo"

In case you might still need support for an ancient browser that doesn't support this feature, this is polyfill suggested by MDN:

If (!String.prototype.trim) ( String.prototype.trim = function () ( return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); ); )


1

I have a lib that uses trim. so solved it with the following code.

String.prototype.trim = String.prototype.trim || function()( return jQuery.trim(this); );


1

If(!String.prototype.trim)( String.prototype.trim = function()( return this.replace(/^\s+|\s+$/gm,""); ); )

It differs from previous answers by adding the m flag.

The m flag will search for text using multiple linear features. In this mode, the pattern start and end mark (^$) is inserted before and after the newline character (\n).


0

I don't know what kind of bugs can hide here, but I use this:

Var some_string_with_extra_spaces=" goes here " console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/))

Or this if the text contains inputs:

Console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/))

New try:

Console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/))


0

I wrote this function for trim when that trim() function was not available in JS back in 2008. Some of the older browsers still don't support the .trim() function and I hope this function can help someone.

CUTTING FUNCTION

Function trim(str) ( var startpatt = /^\s/; var endpatt = /\s$/; while(str.search(startpatt) == 0) str = str.substring(1, str.length); while (str.search(endpatt) == str.length-1) str = str.substring(0, str.length-1); return str; )

Explanation: The trim() function takes a string object and removes all leading and trailing spaces (spaces, tabs, and newlines) and returns the trimmed string. This function can be used to trim form inputs to ensure that the correct data is submitted.

As an example, the function can be called as follows.

Form.elements[i].value = trim(form.elements[i].value);


cut string in jquery

i need to trim a string to its first 100 characters using jquery/javascript. it is also possible to scan a string and look for a specific combination keywords, such as #key? Thanks a lot for...


Equivalent to $.trim in Javascript?

$.trim(value); The above jquery code will cut the text. I need to trim a string using Javascript. I tried: link_content = check ; trim_check=...


How can I trim this javascript string?

How can i trim this string in javascript/jquery £0.00 it has left and right spaces which i can just remove with trim functions() but I want to remove this £ and get the value 0.00.


How to trim a string to N characters in Javascript?

How can I, using Javascript, create a function that will trim a string passed as an argument to a given length also passed as an argument. For example: var string =...


trim string from first number in string in javascript

I have a string IX - delivery received 1/15/2018 9:34:00 AM I want a string like IX - delivery received in JavaScript. I'm going as far as var finalname = title.replace(//g, ""); var...


Trim string at both ends with javascript

Possible Duplicate: How to trim a string in javascript? I have below line which comes from ajax response \r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\tERROR: Profile: NOT SUCCESS\nCODE: 2\nCATEGORY:...


Looking to trim string with javascript/regex

I'm looking for some help with JavaScript/Regex when trying to format a string of text. I have the following IDs: 00A1234/A12 0A1234/A12 A1234/A12 000A1234/A12 I am looking for a way that I can crop everything...


Trim string

Example: abcdefgh\nbbbbbbbbb Whenever I encounter \n, I want to truncate the string to get the newline that comes before the \n. The result should be a section. How can I do this...


Javascript trim multiline string without cutting words

I'm looking for an answer to trim a string to a specific character length without stripping words. I searched questions and found this: javascript shorten string without stripping words I wanted to use @Hamish s answer...


How to cut a string after a certain character in javascript

I have a string like image.jpg. I want to save an image with it's name, so I need to crop the image extension. Any methods in javascript to achieve this.

Learn how to resize and crop images with JavaScript and an HTML5 Canvas element, while using the controls you've seen in photo-editing apps:

In this article, I'll show you how to resize and crop images using the HTML5 element. , and since we're getting into that, let's create some cool image resizing controls along the way that you've seen a lot in photo editing apps.

In a real environment, a website or app might use this technique to resize and create a profile photo before uploading.

We could also do this on the server, however, in this case, potentially large file sizes would be required, which would take a long time. Instead, we can resize the image on the client side before it even loads. That will make everything much faster.

To do this, we will create an HTML5 element and render the image on the canvas at a specific size, and then retrieve the new image data from the canvas as URI data.

Most browsers already support these methods, so you should be able to use this technique right now. However, you need to be aware of some non-browser-supported limitations such as image quality and performance.

Resizing very large images can slow down the browser, or in some cases even crash the application. Therefore, it makes sense to set reasonable limits on the size of the file that can be uploaded. If quality is important to you, you may find this technique impractical because the browser degrades the quality of the image during processing.

Exists a number of techniques that can be used to increase the quality of images scaled from the canvas However, we will not consider them in this article.

You can see the final result in this demo, or you can download the ZIP archive.

Well, now let's get started!

markup

In our demo, we'll start with an existing image:

That's all! This is all the HTML we need for this demo.

css

CSS is also the most minimal. First, let's style the resize container and the image:

Resize-container ( position: relative; display: inline-block; cursor: move; margin: 0 auto; ) .resize-container img ( display: block ) .resize-container:hover img, .resize-container:active img ( outline: 2px dashed rgba(222,60,80,.9); )

Resize-handle-ne, .resize-handle-ne, .resize-handle-se, .resize-handle-nw, .resize-handle-sw ( position: absolute; display: block; width: 10px; height: 10px; background: rgba(222,60,80,.9); z-index: 999; ) .resize-handle-nw ( top: -5px; left: -5px; cursor: nw-resize; ) .resize-handle- sw ( bottom: -5px; left: -5px; cursor: sw-resize; ) .resize-handle-ne ( top: -5px; right: -5px; cursor: ne-resize; ) .resize-handle-se ( bottom: -5px; right: -5px; cursor: se-resize; )

JavaScript

In JavaScript, we start by defining some variables and initializing the Canvas and the target image:

var resizeableImage = function(image_target) ( var $container, orig_src = new Image(), image_target = $(image_target).get(0), event_state = (), constraint = false, min_width = 60, min_height = 60, max_width = 800, max_height = 900, resize_canvas = document.createElement("canvas"); )); resizeableImage($(".resize-image"));

Next, we create an init function that will be called immediately on boot. This function wraps an image in a container, creates resize handles, and creates a copy of the original image that is used for resizing.

We also assign the jQuery object for the container element to a variable so we can refer to it later and add a mousedown event listener that detects when someone starts dragging one of the markers:

var resizeableImage = function(image_target) ( // ... init = function()( // Create a new image with a copy of the original src // When we resize an image, we always base it on this copy orig_src.src=image_target.src ; // Add resize handles $(image_target).wrap("

").before(" ").before(" ").after(" ").after(" "); // Get container variables $container = $(image_target).parent(".resize-container"); // Add events $container.on("mousedown", ".resize-handle", startResize); ); //... init(); )

The startResize and endResize functions just tell the browser to start tracking where the mouse is moving and stop tracking:

startResize = function(e)( e.preventDefault(); e.stopPropagation(); saveEventState(e); $(document).on("mousemove", resizing); $(document).on("mouseup", endResize ); ); endResize = function(e)( e.preventDefault(); $(document).off("mouseup touchend", endResize); $(document).off("mousemove touchmove", resizing); );

Before we start tracking the position of the mouse, we need to take a snapshot of the dimensions and other key data of the container.

We store them in a variable called event_state and use it later as a starting point when changing the height and width:

saveEventState = function(e)( // Save the original event parameters and container state event_state.container_width = $container.width(); event_state.container_height = $container.height(); event_state.container_left = $container.offset().left ; event_state.container_top = $container.offset().top; event_state.mouse_x = (e.clientX || e.pageX || e.originalEvent.touches.clientX) + $(window).scrollLeft(); event_state.mouse_y = (e.clientY || e.pageY || e.originalEvent.touches.clientY) + $(window).scrollTop(); // This is a patch for mobile safari // For some reason it can't copy touch properties directly if (typeof e.originalEvent.touches !== "undefined")( event_state.touches = ; $.each(e.originalEvent.touches, function(i, ob)( event_state.touches[i] = (); event_state.touches [i].clientX = 0+ob.clientX; event_state.touches[i].clientY = 0+ob.clientY; )); ) event_state.evnt = e; )

The resizing function does most of the work. This function is constantly called when the user drags one of the resizing handles. Each time this function is called, we create a new width and height by calculating the ratio between the current mouse position and the original position of the corner the user has dragged:

resizing = function(e)( var mouse=(),width,height,left,top,offset=$container.offset(); mouse.x = (e.clientX || e.pageX || e.originalEvent.touches .clientX) + $(window).scrollLeft(); mouse.y = (e.clientY || e.pageY || e.originalEvent.touches.clientY) + $(window).scrollTop(); width = mouse. x - event_state.container_left; height = mouse.y - event_state.container_top; left = event_state.container_left; top = event_state.container_top; if(constrain || e.shiftKey)( height = width / orig_src.width * orig_src.height; ) if(width > min_width && height > min_height && width< max_width && height < max_height){ resizeImage(width, height); // Без этого Firefox не будем пересчитывать размеры изображения, пока перетаскивание не завершилось $container.offset({"left": left, "top": top}); } }

We then add an option to limit the size of the image when switching with Shift keys or a variable.

Finally, we resize the image, but only if the new width and height are within the minimum and maximum values ​​of the variables we set at the beginning.

Note: Since we're actually resizing the image, not just the height and width attributes, you might want to consider limiting how often you can call resizeImage for performance reasons. This is called debouncing or throttling.

Actual image resizing

You can simply draw an image with drawImage. We first set the height and width of the canvas and always use original copy full size image. We then use toDataURL on the canvas to get a Base64 encoded version of the newly modified image and place it on the page.

The clipping section has a full explanation of all the options that can be used with the drawImage method:

resizeImage = function(width, height)( resize_canvas.width = width; resize_canvas.height = height; resize_canvas.getContext("2d").drawImage(orig_src, 0, 0, width, height); $(image_target).attr( "src", resize_canvas.toDataURL("image/png")); );

Too easy? There is one small caveat: the image must be hosted on the same domain as the page, or on a server with cross-origin exchange capability (CORS). IN otherwise you may have problems with errors " damaged canvas«.

Resizing from different angles

You should now have a working demo. But that is not all. On this moment, it doesn't yet work so that resizing happens as if we're dragging the bottom right corner, no matter which corner we're resizing the image from.

We need to ensure that the image can be resized from any angle. To do this, we need to understand the behavior of our demo model.

When resizing, the corner we're dragging, as well as the sides adjacent to it, should move, while the opposite corner and the sides adjacent to it should stay in place:

When we change the width and height of the image, the right and bottom edges move, while the top and left edges stay in place. This means that by default, images are resized from the bottom right corner.

We can't change this default behavior, but when resizing from any corner other than the bottom right corner, we can change the overall position of the image so that the opposite corner and adjacent edges appear to stay in place. Let's update our resizing function:

resizing = function(e)( var mouse=(),width,height,left,top,offset=$container.offset(); mouse.x = (e.clientX || e.pageX || e.originalEvent.touches .clientX) + $(window).scrollLeft(); mouse.y = (e.clientY || e.pageY || e.originalEvent.touches.clientY) + $(window).scrollTop(); // Image Position depending on the angle we're dragging if($(event_state.evnt.target).hasClass("resize-handle-se"))( width = mouse.x - event_state.container_left; height = mouse.y - event_state .container_top; left = event_state.container_left; top = event_state.container_top; ) else if($(event_state.evnt.target).hasClass("resize-handle-sw"))( width = event_state.container_width - (mouse.x - event_state.container_left); height = mouse.y - event_state.container_top; left = mouse.x; top = event_state.container_top; ) else if($(event_state.evnt.target).hasClass("resize-handle-nw" ))( width = event_state.container_width - (mouse.x - event_state.container_left); height = event_state.container _height - (mouse.y - event_state.container_top); left = mouse.x; top = mouse.y; if(constrain || e.shiftKey)( top = mouse.y - ((width / orig_src.width * orig_src.height) - height); ) ) else if($(event_state.evnt.target).hasClass("resize -handle-ne"))( width = mouse.x - event_state.container_left; height = event_state.container_height - (mouse.y - event_state.container_top); left = event_state.container_left; top = mouse.y; if(constrain | | e.shiftKey)( top = mouse.y - ((width / orig_src.width * orig_src.height) - height); ) ) // Optionally maintain aspect ratio if(constrain || e.shiftKey)( height = width / orig_src.width * orig_src.height; ) if(width > min_width && height > min_height && width< max_width && height < max_height){ // Для увеличения производительности вы можете ограничить количество вызовов resizeImage() resizeImage(width, height); // Без этого Firefox не будет пересчитывать размеры изображения, пока перетаскивание не завершилось $container.offset({"left": left, "top": top}); } }

Now our code checks which of the resize-handles is being dragged and moves our image so that the corresponding corner appears to stay still.

Image movement

Now that we can resize an image by dragging any of its corners, you may have noticed that we can inadvertently reposition the image on the page.

Now we need to make sure that the image comes back to the center of the frame. In the init function, let's add another event listener, similar to the one we already created earlier:

init = function()( //... $container.on("mousedown", "img", startMoving); )

Now we add the startMoving and endMoving functions, similar to how we added startResize and endResize:

startMoving = function(e)( e.preventDefault(); e.stopPropagation(); saveEventState(e); $(document).on("mousemove", moving); $(document).on("mouseup", endMoving ); ); endMoving = function(e)( e.preventDefault(); $(document).off("mouseup", endMoving); $(document).off("mousemove", moving); );

In the moving function, we need to calculate a new position for the top left edge of the container. It will be equal to the current mouse position offset from the left upper corner to the mouse when we started dragging the image:

moving = function(e)( var mouse=(); e.preventDefault(); e.stopPropagation(); mouse.x = (e.clientX || e.pageX) + $(window).scrollLeft(); mouse .y = (e.clientY || e.pageY) + $(window).scrollTop(); $container.offset(( "left": mouse.x - (event_state.mouse_x - event_state.container_left), "top" : mouse.y - (event_state.mouse_y - event_state.container_top) )); );

Image cropping

Now that we can resize the image, you might want to crop it. Instead of giving users the ability to crop an image to any size or shape, let's create a frame that has the exact dimensions we want and ask users to place an image inside that frame.

They will be able to determine the scale and position of the cropped frame in the original image, but we, in turn, will be sure that the final image will always have the same shape and size.

To do this, we need to add the following HTML code:

The styles for the overlay frame are very important, especially the position, width, and height, as they are used to determine which part of the image will be cropped.

It is also important to remember that the frame should always be visible against a background of any color. That is why in my example I used a translucent white outline around the main window:

Overlay ( position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; z-index: 999; width: 200px; height: 200px; border: solid 2px rgba( 222,60,80,.9); box-sizing: content-box; pointer-events: none; ) .overlay:after, .overlay:before ( content: ""; position: absolute; display: block; width: 204px; height: 40px; border-left: dashed 2px rgba(222,60,80,.9); border-right: dashed 2px rgba(222,60,80,.9); ) .overlay:before ( top: 0; margin-left: -2px; margin-top: -40px; ) .overlay:after ( bottom: 0; margin-left: -2px; margin-bottom: -40px; ) .overlay-inner:after, .overlay -inner:before ( content: ""; position: absolute; display: block; width: 40px; height: 204px; border-top: dashed 2px rgba(222,60,80,.9); border-bottom: dashed 2px rgba(222,60,80,.9); ) .overlay-inner:before ( left: 0; margin-left: -40px; margin-top: -2px; ) .overlay-inner:after ( right: 0; margin-right: -40px; margin-top: -2px; ) .btn-crop ( position: absolute; vertica l-align: bottom; right: 5px; bottom: 5px; padding: 6px 10px; z-index: 999; background-color: rgb(222,60,80); border: none border-radius: 5px color: #FFF; )

Add the following function and event listener to JavaScript:

init = function()( //... $(".js-crop").on("click", crop); ); crop = function()( var crop_canvas, left = $(".overlay").offset().left - $container.offset().left, top = $(".overlay").offset().top - $container.offset().top, width = $(".overlay").width(), height = $(".overlay").height(); crop_canvas = document.createElement("canvas"); crop_canvas. width = width; crop_canvas.height = height; crop_canvas.getContext("2d").drawImage(image_target, left, top, width, height, 0, 0, width, height); window.open(crop_canvas.toDataURL("image /png")); )

The crop function is similar to the resizeImage function, except that instead of passing it a height and width value, we get the height and width from the overlay element.

For clipping, the drawImage canvas method requires nine parameters. The first parameter is the source of the image. The next four parameters specify how much of the original image is used (the clipping box). The last four parameters specify where on the canvas to display the image and at what size.

Adding touch events

Mousedown and mouseup have equivalent touch events, touchstart and touchend , and mousemov has an equivalent touchmove event. Someone who called these events clearly lacked a sense of humor, otherwise he might well have called them “touchdown” and “touchup”.

Let's add touchstart and touchend wherever we have mousedown and mouseup , and replace mousemove with touchmove :

// In init()... $container.on("mousedown touchstart", ".resize-handle", startResize); $container.on("mousedown touchstart", "img", startMoving); //In startResize() ... $(document).on("mousemove touchmove", moving); $(document).on("mouseup touchend", endMoving); //In endResize()... $(document).off("mouseup touchend", endMoving); $(document).off("mousemove touchmove", moving); //In startMoving()... $(document).on("mousemove touchmove", moving); $(document).on("mouseup touchend", endMoving); //In endMoving()... $(document).off("mouseup touchend", endMoving); $(document).off("mousemove touchmove", moving);

Since we're resizing the image, it's fair to expect that some users will want to use common actions like stretching the image. There is such a library Hammer , which contains many convenient tools for working with touch events.

But since we only need stretching, we can do without it. Now I will show how easy it is to create a stretch without the help of a third-party library.

You may have noticed that the saveEventState function already stores the original touch data; now we need it.

First, we check if the event contains two "touches" and measure the distance between them. We mark this as the initial distance, and then measure how much this distance changes during the movement. Let's update the moving function:

moving = function(e)( var mouse=(), touches; e.preventDefault(); e.stopPropagation(); touches = e.originalEvent.touches; mouse.x = (e.clientX || e.pageX || touches.clientX) + $(window).scrollLeft(); mouse.y = (e.clientY || e.pageY || touches.clientY) + $(window).scrollTop(); $container.offset(( " left": mouse.x - (event_state.mouse_x - event_state.container_left), "top": mouse.y - (event_state.mouse_y - event_state.container_top) )); // Track Stretch During Move if(event_state.touches && event_state.touches.length > 1 && touches.length > 1)( var width = event_state.container_width, height = event_state.container_height; var a = event_state.touches.clientX - event_state.touches.clientX; a = a * a; var b = event_state.touches.clientY - event_state.touches.clientY; b = b * b; var dist1 = Math.sqrt(a + b); a = e.originalEvent.touches.clientX - touches.clientX; a = a * a;b = e.originalEvent.touches.clientY - touches.clientY;b = b * b;var dist2 = Math.sqrt(a+b); var ratio = dist2 /dist1; width = width * ratio; height = height * ratio; // To improve performance, you can limit the number of calls to resizeImage() resizeImage(width, height); ) );

We divide the current distance by the initial distance to determine the ratio and apply it accordingly to scale the image. We calculate the new width and height and then resize the image:

That's all. Watch the demo again or download the ZIP archive.

In testing, I saw that Chrome blocks the browser's default response to stretch, but Firefox works fine.

I hope you found this article useful to you. I encourage you to read other articles on draggable elements and file upload methods, and find out how other people combine these methods to create beautiful user interfaces.

This publication is a translation of the article " RESIZING AND CROPPING IMAGES WITH CANVAS» prepared by a friendly project team

Warning: Although String.prototype.substr(…) is not strictly deprecated (as in "removed from the Web standards"), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.

The substr() method returns a portion of the string, starting at the specified index and extending for a given number of characters afterward.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

str .substr(start[, length])

Parameters

start The index of the first character to include in the returned substring. optional length. The number of characters to extract.

return value

A new string containing the specified part of the given string.

Description

substr() extracts length characters from a string , counting from the start index.

If start is a positive number, the index starts counting at the start of the string. Its value is capped at str.length .
If start is a negative number, the index starts counting from the end of the string. Its value is capped at -str.length .
Note: In Microsoft JScript, negative values ​​of the start argument are not considered to refer to the end of the string.

If length is omitted, substr() extracts characters to the end of the string.
If length is undefined , substr() extracts characters to the end of the string.
If length is a negative number, it is treated as 0.

For both start and length , NaN is treated as 0.

Examples

Using substr()

var aString = "Mozilla"; console.log(aString.substr(0, 1)); // "M" console.log(aString.substr(1, 0)); // "" console.log(aString.substr(-1, 1)); // "a" console.log(aString.substr(1, -1)); // "" console.log(aString.substr(-3)); // "lla" console.log(aString.substr(1)); // "ozilla" console.log(aString.substr(-20, 2)); // "Mo" console.log(aString.substr(20, 2)); // ""

Polyfill

Microsoft's JScript does not support negative values ​​for the start index. To use this feature in JScript, you can use the following code:

// only run when the substr() function is broken if ("ab".substr(-1) != "b") ( /** * Get the substring of a string * @param (integer) start where to start the substring * @param (integer) length how many characters to return * @return (string) */ String.prototype.substr = function(substr) ( return function(start, length) ( // call the original method return substr. call(this, // did we get a negative start, calculate how much it is from the beginning of the string // adjust the start parameter for negative value start< 0 ? this.length + start: start, length) } }(String.prototype.substr); }

Specifications

Specification
ECMAScript Latest Draft (ECMA-262)
The definition of "String.prototype.substr" in that specification.

Browser compatibility

The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

DesktopMobileserver
ChromeedgeFirefoxInternet ExplorerOperasafariandroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
substr

Deprecated

Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support YesSafari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes

Legend

Full support Full support deprecated. Not for use in new websites. deprecated. Not for use in new websites.
Internet