使用Javascript从字符串中提取子字符串 [英] Extract substring out of a string using Javascript

查看:94
本文介绍了使用Javascript从字符串中提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部

我将以下html作为javascript中的字符串.我需要提取值"中的字符串,并用指定的分隔符"|"分隔并放入两个变量.

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.

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.

推荐答案

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

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:

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

这篇关于使用Javascript从字符串中提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆