javascript 使用Javascript从字符串中提取子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5810431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:26:02  来源:igfitidea点击:

Extract substring out of a string using Javascript

javascriptjqueryregex

提问by Jake

All,

全部,

I have the following html as a string in javascript. I need to extract the string in "value", split by the specified delimeter "|" and put in two variables.

我有以下 html 作为 javascript 中的字符串。我需要提取“value”中的字符串,由指定的分隔符“|”分割 并放入两个变量。

var html = '<div><input name="radBtn" class="radClass" style="margin:auto;" 
       onclick="doSomething();"
       value="Apples|4567" type="radio">
</div>';

Required output is two variables having the following values:

所需的输出是具有以下值的两个变量:

fruitName = Apples
fruitNumber = 4567

Note: There can be many radio buttons with the same name.

注意:可以有许多同名的单选按钮。

回答by Neil

If you can assume that your HTML is always going to be simple (i.e. only one value attribute, and nothing else that looks like a value attribute), then you can do something like this:

如果你可以假设你的 HTML 总是很简单(即只有一个 value 属性,没有其他看起来像 value 属性的东西),那么你可以这样做:

var fruit = html.match(/value="(.*?)\|(.*?)"/);
if (fruit) {
    fruitName = fruit[1];
    fruitValue = fruit[2];
}

回答by Karl Laurentius Roos

Here's how you can do it:

您可以这样做:

$("input[name='radBtn']").click(function(){
    var val = $(this).val();
    val = val.split("|");

    var fruit = val[0];
    var number = val[1];
});

回答by Ken Redler

Here's one way:

这是一种方法:

var fruit = (function() {
    var fruits = $(html).find('.radClass').val().split('|');
    return {
        fruitName: fruits[0],
        fruitNumber: fruits[1]
    };
}());

You'll get an object like this:

你会得到一个这样的对象:

fruit.fruitName // Apples
fruit.fruitNumber // 4567

回答by mattsven

var div = document.createElement("div");
div.innerHTML = '<input name="radBtn" class="radClass" style="margin:auto;" onclick="doSomething();" value="Apples|4567" type="radio"></div>';  

var str = div.getElementsByTagName("input")[0].split("|");

var fruitName = str[0];
var fruitNumber = str[1];

/*
Now,
fruitName = "Apples"
and
fruitNumber = 4567
*/

回答by Rory McCrossan

$(function() {
    $("INPUT[name=radBtn]").click(function() {
        var value = $(this).val().split("|");
        var fruitName = value[0];
        var fruitNumber = value[1];

        // Add to an array, ajax post etc. whatever you want to do with the data here
    });
});

回答by John K.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

see: How to parse a string in javascript?

请参阅:如何在 javascript 中解析字符串?