0

in vb6 there was a very handy function for string manipulation which could put a character at a certain position of another string and i'm looking for an extended jquery equivalent.

let's say i'm having this string:

var mystring = "__1__";

when applying the function:

var mystring = mid(mystring,4,"x");

it should return __1x_

another example:

var mystring = "";
var mystring = mid(mystring,5,"x");

should return: ____5

i know it requires string manipulation using substr but i was wondering if there's a more elegant way? thanks

user2246674
  • 7,621
  • 25
  • 28
Fuxi
  • 329
  • 2
  • 6
  • 15
  • You use pure Javascript, not jQuery. Please check the following question, which has already been answered: [JavaScript: How can I insert a string at a specific index](http://stackoverflow.com/questions/4313841/javascript-how-can-i-insert-a-string-at-a-specific-index) – Geeky Guy Sep 06 '13 at 22:33
  • Are you talking about this function? http://msdn.microsoft.com/en-us/library/05e63829%28v=vs.90%29.aspx I'm not familiar with the inserting behavior – Jason Sperske Sep 06 '13 at 22:47

1 Answers1

1

This can be simulated in several ways although there is no such specific function (splice is standard only on Arrays, not Strings).

The easiest one-expression way I know of is with a String.replace when adding to a location "past the end of the string" is not required. Of course String.slice is also a perfectly valid approach, and may be arguably easier to understand.

mystring = "__1__"
// where 3 represents the "characters to skip before inserting"
// and 1 represents the "number of characters to replace"
midstr = mystring.replace(/([^]{3})[^]{0,1}/, "$1x")

Neither the above nor a basic slice will work like the 2nd example without additional prepend-as-needed logic.

user2246674
  • 7,621
  • 25
  • 28