JavaScript拆分字符串错误

时间:2015-05-18 18:54:18

标签: javascript html

我正在尝试拆分此字符串

"http://localhost/webproject/products.html?product=Apple%20iPhone%206%20With%20FaceTime%20class="

到这个

"Apple iphone 6 with Facetime"

但我的代码只将其拆分为

"Apple iphone 6 with Facetime class"

当我试图删除类字并提醒字符串时,它显示为空。当我提醒split5时,它显示为NaN

var url = window.location.href;
var split = url.split('=');
var split2 = split[1];
var split3 = split2.replace(/20/g,"");
var split4 = split3.replace(/%/g, " ");
var split5 = split4.count-5;
var split6 = split4.slice(0, split5);
alert(split6);

4 个答案:

答案 0 :(得分:1)

@Karim,正在进行的是你正在使用替换,然后在这些字符的位置上计算-5。这就是它返回NaN的原因。

这是你想要的:



var url = 'http://localhost/webproject/products.html?product=Apple%20iPhone%206%20With%20FaceTime%20class=';
var split = url.split('=');
var split2 = split[1];
var split3 = split2.split('%20');
alert(split3.join(' '));




答案 1 :(得分:0)

您可以按&#39;%20&#39;拆分字符串,使用 <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link href='http://fonts.googleapis.com/css?family=Lato:400,100,300,700,900' rel='stylesheet' type='text/css'> <link rel="stylesheet" media="screen and (min-width: 1024px)" href="style/main.css"> <link rel="stylesheet" media="screen and (max-width: 480px)" href="style/mobile.css"> <link rel="stylesheet" href="style/typography.css"> </head> 删除最后一个值,然后加入结果:

&#13;
&#13;
pop()
&#13;
&#13;
&#13;

有关Array.prototype.pop()

的更多信息

答案 2 :(得分:0)

您可以使用decodeURI()方法做得更好。而不是count,您必须使用length

string没有count属性,这就是你获得NaN1的原因。

var url = window.location.href;
var split = url.split('=');
var split2 = decodeURI(split[1]);
var split5 = split2.length-5;
var split6 = split2.substring(0, split5);
alert(split6);

答案 3 :(得分:0)

此外,作为一个快捷方式,您可以将string.slice方法的第二个参数设置为负数,以从字符串末尾删除那么多字符,例如-5来切掉最后5个字符。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice