9

lets suppose i have string

var string = "$-20455.00"

I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.

var string = "-$20455.00"

How can I achieve this?

6 Answers 6

27

You can use the replace function in Javascript.

var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');

Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/

Sign up to request clarification or add additional context in comments.

Comments

13

You dont have to use arrays. Just do this

string[1] + string[0] + string.slice(2)

Comments

3

You can split to an array, and then reverse the first two characters and join the pieces together again

var string = "$-20455.00";
    
var arr = string.split('');
    
var result =  arr.slice(0,2).reverse().concat(arr.slice(2)).join('');

document.body.innerHTML = result;

Comments

2

try using the "slice" method and string concatenation:

stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)

edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.

Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.

Comments

0

var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));

document.body.innerHTML = result;

Comments

0
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

1 Comment

Add some explanation, even though your code is explanatory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.