How can I match part of a string to jQuery?

Say a line like

"... width = 600 height = 1200 ...".

I want to get the line after "width="and before " ", which 600.

How can i do this?

+3
source share
3 answers

Use regex with match () function :

var str = "... width=600 height=1200 ...",
    width = str.match(/\bwidth=(\d+)/);

if (width)
    alert(width[1]); 
    //-> 600

The proposed regular expression searches for the word boundary ( \b), followed by a literal string width=, followed by 1 or more digits, which are also written as a subexpression ( (\d+)). This sub-expression capture is added to the array returned by the match.

+13
source

:

var matches = "... width=600 height=1200 ...".match(/width=(\d+)/);
if (matches) {
    alert(matches[1]);
}

. , , , , .

+3

lonesomeday, , , - , , .

- :

var str = "width=600 height=1200";
$('<div ' + str + '>').attr('width');

, HTML .


, OP:

width:

<DIV><EMBED 
    height=311 type=application/x-shockwave-flash
    width=700 src=http://www.youtube.com/v/0O2Rq4HJBxw
    allowfullscreen="true" allowscriptaccess="always"
    wmode="transparent">
</EMBED></DIV>

.

var str = "<DIV><EMBED height ... etc";
$(str).find('embed').attr('width');

" HTML" rant/freakout, .

+2

Source: https://habr.com/ru/post/1772638/


All Articles