简体   繁体   中英

Find the first string after character

I am trying to find the first character after a special character. For example: String: dog/11/99 I want jQuery to find 1(the character after the first /) and then 9(the character after the second /)

<table border="1">
   <tr><td class="abc">apple</td></tr>
   <tr><td class="abc">ball</td></tr>
   <tr><td class="abc">cat/55/77</td></tr>
   <tr><td class="abc">dog/11/99</td></tr>
</table>

I need to look through the whole table and then give me the character after the special character.

Any idea how I can accomplish that?

Try using the Regex:

/\/(.)/g

That will return the first character after any / .
For example:

var match, regex = /\/(.)/g;
while (match = regex.exec('dog/11/99')) console.log(match);
// ["/1", "1", index: 3, input: "dog/11/99"]
// ["/9", "9", index: 6, input: "dog/11/99"]

with match[1] being your desired character.

You can use .match() with RegExp /\\W/ to match character that is not a word character, .index of returned array, String.prototype.slice() , bracket notation to get selected character at index of string.

 var str = document.querySelector("table tr:last-child td").textContent; var index = str.match(/\\W/).index; var res1 = str[index + 1]; var res2 = str.slice(index, str.length).match(/\\W/).index; var res2 = str[ str.slice(index + 1, str.length).match(/\\W/).index + 1 + index + 1 ]; console.log(res1, res2); 
 <table border="1"> <tr><td class="abc">apple</td></tr> <tr><td class="abc">ball</td></tr> <tr><td class="abc">cat/55/77</td></tr> <tr><td class="abc">dog/11/99</td></tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM