insert a string into another string at a certain position?

C

CK

Hi All,
Theis should be easy. I need to insert a string into an exisitng string?
Example
var string1 = "sweet";
var string2 = "bbb";

I want to modify string1 to be "swebbbet";
I know this must be farely simple but a little more than simple
concatenation is required.
Thanks in advance for any solutions.

Regards,
CK
 
L

Lasse Reichstein Nielsen

CK said:
Theis should be easy. I need to insert a string into an exisitng string?
Example
var string1 = "sweet";
var string2 = "bbb";

I want to modify string1 to be "swebbbet";

string1 = "swebbbet";

But seriously, I assume you have some position where you want it.
Then you can build the result by concatenating substrings:

string1 = string1.substring(0,3) + string2 + string1.substring(3);

You can't modify the string in the variable "string1" itself,
you can only create a new string and assign that to the variable.
Strings are immutable.

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue, 25 Apr 2006
23:11:15 remote, seen in Lasse Reichstein
Nielsen said:
string1 = "swebbbet";

But seriously, I assume you have some position where you want it.

There must be some definition (even if it is "at random"), but the
condition may be given other than as a number.
Then you can build the result by concatenating substrings:

string1 = string1.substring(0,3) + string2 + string1.substring(3);

Or by

string1 = string1.replace(/(.{3})/, "$1" + string2) // position 3
string1 = string1.replace(/(e)/, "$1" + string2) // after first e
string1 = string1.replace(/(e[^e]+)/, string2 + "$1") // before ...
// ... the first e followed by a non-e
string1 = string1.replace(/(..)$/, string2 + "$1") // two from end
string1 = string1.replace(/ee/g, "e" + string2 + "e") // in every 'ee'

<URL:http://www.merlyn.demon.co.uk/js-valid.htm>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top