2

I need to replace first and last character in random string. Why this code doesn't work?

function symbExchange(line) {  
    var tmp = line[0];  
    var str = line.replace(line[0], line[line.length-1]);  
    var str2 = str.replace(str[str.length-1], tmp);  
    return str2;
}
1
  • str.replace() will replace the first occurrence. Commented Mar 16, 2018 at 11:21

5 Answers 5

0

That's because the replace function returns a new string with some or all matches of a pattern replaced by a replacement.

If you need to swap characters, you can use a regex in your case (but this is not the best implementation):

function symbExchange(line) {  
    var tmp = line[0];  
    var str = line.replace(new RegExp('^' + line[0]), line[line.length-1]);  
    var str2 = str.replace(new RegExp(str[str.length-1] + '$'), tmp);  
    return str2;
}
Sign up to request clarification or add additional context in comments.

Comments

0

It does not work because replace function will replace the first occurrence

try this :

function symbExchange(line) {  
    var first = line[0];  
    var last = line[line.length-1];  
    line[0] = last;
    line[line.length-1] = first
    return str2;
}

Comments

0

This line replaces first occurence of character that is same as last character. Not the last character itself.

var str2 = str.replace(str[str.length-1], tmp);  

possible solution is not to use replace function:

function symbExchange(line) {  
    var startCh = line[0];  
    var endCh = line[line.length-1];
    var str = line;
    str[0] = endCh;
    str[str.length-1] = startCh;
    return str;
}

Comments

0

String.Replace when used with a string argument will only replace the first occurrence of that string. You either need to use regex as an argument, or do a split 'n' join. Which one is better /faster will depend on the length of your string and number of occurrences to replace.

var src = "helloworldhello";
var dest = src.replace( /hello/g , "goodbye");
console.log(dest);

or

var src = "helloworldhello";
var dest = src.split("hello").join("goodbye");

Comments

0

Use swapping characters after converting string to array and then to string

function symbExchange(line) {  

line = line.split("");
temp=line[0]
line[0]=line[line.length-1]
line[line.length-1]=temp
return line.join("")
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.