In general, you need to output the user id from the id to the comma. In this code, displays "id50,", you only need "50". How?)
text = 'id50, 4124fdgfgdfg'; if(text.match('id[0-9].*,')){ komy = text.match('id[0-9].*,'); alert(komy); }
In general, you need to output the user id from the id to the comma. In this code, displays "id50,", you only need "50". How?)
text = 'id50, 4124fdgfgdfg'; if(text.match('id[0-9].*,')){ komy = text.match('id[0-9].*,'); alert(komy); }
Using the regular expression ^id(\d+),.*$
(Captures the number in brackets after id, and before the comma). You can immediately capture the second part ( 4124fdgfgdfg
), with the following expression: /^id(\d+), (.*)$/
.
Working example:
str = 'id42, 4124fdgfgdfg'; if (m = str.match(/^id(\d+), (.*)$/)) { console.log(m[1], m[2]) }
Gives to the console (you can click the "Run code" button to check):
42 4124fdgfgdfg
Here is a good description of match
in Russian: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/match
Here https://regex101.com/ you can play online with regular expressions and immediately see the result. Here is your example with tests and comments: https://regex101.com/r/nX1rF5/2
match
or exec
will have to cut the bikes, otherwise the Cannot read property '1'
- Mr. BlackA bunch of options:
You can correct the expression itself and will work:
// (?<=id) - смотрит позитивно назад, но не берёт в результат // (?=,) - смотрит позитивно вперёд, но не берёт в результат // + перед выражением пытается привести результат к Number // // Вернётся либо ["50"], либо null; // массив с одним элементом попытается привести первый элемент // null станет 0 // Используйте эти знания на благо Вашей проверки :) console.info(+/(?<=id)\d*(?=,)/.exec('id50, 4124fdgfgdfg')); // 50
You can, of course, use the good old groups (you can even do the named ones ):
// С помощью тернарного оператора проверяем на null // Если null - вернём 0 // Если есть результат - приводим к Number 1 элемент (в 0 - всё совпадение, т. е. id50,) console.info((r = /id(\d*),/.exec('id50, 4124fdgfgdfg')) ? +r[1] : 0); // 50
It is possible to pervert the type String.prototype.split
, where the number is saved with the help of the same groups, but why use a hacksaw for hammering nails?
When a match
or exec
to use additional checks, otherwise the error Cannot read property '1' is possible
split
will either find or not ( undefined )
text = 'id50, 4124fdgfgdfg'; t = text.split(/id(\d+), (.*)/); console.log(t[1], t[2]);
text = ' id50, 4124fdgfgdfg'; console.log(text.replace(/id(\d+)\s*,.*|./gi, '$1')) text = ' id50, 4124fdgfgdfg id100,'; console.log(text.replace(/id(\d+)\s*,.*|./gi, '$1')) text = ' id, 4124fdgfgdfg'; console.log(text.replace(/id(\d+)\s*,.*|./gi, '$1'))
No, but you can (along with id
):
/id\d[^,]*/
Source: https://ru.stackoverflow.com/questions/541508/
All Articles