如何在JavaScript中解析值?

时间:2015-05-18 09:42:20

标签: javascript

示例字符串:

  

(13.910074099911057%2C + 100.37796020507812)%2C(13.840746785080066%2C + 100.27908325195312)%2C(13.712703652698178%2C + 100.33126831054688)%2C(13.7620619168356%2C + 100.50979614257812)

格式正确:

  

13.910074099911057,100.37796020507812 13.840746785080066,100.27908325195312 13.712703652698178,100.33126831054688 13.7620619168356,100.50979614257812

示例代码:

var locate = window.location
document.GetPerimeter.Perimeter.value = locate

var text = document.GetPerimeter.Perimeter.value

function CopyPerimeter(str) {
    theleft = str.indexOf("=") + 1;
    theright = str.lastIndexOf("&");             

    return (str.substring(theleft, theright));
}

var ShowPerimeter = CopyPerimeter(text)
document.GetPerimeter.Perimeter.value = ShowPerimeter


function decode() {
    var obj = document.getElementById('Perimeter');
    var encoded = obj.value;
    obj.value = decodeURIComponent(encoded.replace(/\+/g, ""));
}
decode();

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式来解析Javascript中的文本。只需使用myString.match('myRegEx')函数,它将返回一个包含已解析值的数组。请注意,值仍然是文本格式,因此如果您想要使用它们,则需要将它们转换为浮点数。

这个正则表达式可能会起作用:/[-+]?\d+\.?\d*[^)C%]/g

如果您需要修改正则表达式以匹配其他值,请尝试使用在线助手,如下所示:

http://www.regexr.com/

https://regex101.com/#javascript

我希望我理解你的问题是正确的。

答案 1 :(得分:0)

这是将JAVASCRIPT字符串解析为所需字符串的脚本:

var str = "(13.910074099911057%2C+100.37796020507812)%2C(13.840746785080066%2C+100.27908325195312)%2C(13.712703652698178%2C+100.33126831054688)%2C(13.7620619168356%2C+100.50979614257812)";
var strParsed = "";
var percentCame = 0;
for (var i=0; i < str.length; i++) {
    if( (str[i]!="(") && (str[i]!=")") ){
        if( (str[i]=="%") ){
            percentCame = 1;
        }
        if(percentCame==1){
            i += 4;
            strParsed = strParsed + "," + str[i];
            percentCame = 0;
        }
        else{
            strParsed = strParsed + str[i];
        }
    }
}