javascript无法取下字符串的第一个字母

时间:2013-04-12 07:29:00

标签: javascript replace substring

我有一个js函数,一旦完成将计算基本代数方程。出于某种原因,它不会让我替换数组中字符串的第一个字符。我之前在这个函数中使用过它,但它现在不起作用了。我尝试过使用.replace()和.substring()。

以下是我尝试过的代码:

// this is what i've been testing it on
// $problem[o][j] = +5
var assi = $problem[0][j].charAt(0); // Get the first character, to replace to opposite sign
switch (assi){
  case "+":
    console.log($problem[0][j]);
    $problem[0][j].replace("+","-");
    console.log($problem[0][j]);
    break;
}

以上输出到控制台:

> +5
> +5

我尝试了下一个代码:

// Second code i tried with $problem[0][j] remaining the same
switch(assi){
  case "+":
    console.log($problem[0][j]);
    $problem[0][j].substring(1);
    $problem[0][j] = "-" + $problem[0][j];
    console.log($problem[0][j]);
    break;
}

输出到控制台:

> +5
> -+5

3 个答案:

答案 0 :(得分:4)

字符串是不可变的 - 某个字符串的内容无法更改。您需要使用替换创建一个新字符串。您可以将此新字符串分配给旧变量,使其“看起来像”修改。

var a = "asd";
var b = a.replace(/^./, "b"); //replace first character with b
console.log(b); //"bsd";

重新分配:

var a = "asd";
a = a.replace(/^./, "b"); //replace first character with b
console.log(a); //"bsd";

如果你想翻转一个数字的符号,可能更容易与-1相乘。

答案 1 :(得分:1)

你需要用新的字符串替换实际的字符串

$problem[0][j] = $problem[0][j].replace("+","-");

答案 2 :(得分:1)

.replace()不会对字符串进行更改,只需返回一个包含所做更改的新字符串。

//这没有任何作用

problem[0][j].replace("+","-");

//这会保存替换后的字符串

problem[0][j] = problem[0][j].replace("+","-");
相关问题