Click here to Skip to main content
15,882,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is white space in js regex?
I am trying to find whitespace using the lastindexof function, but it doesn't work.

What I have tried:

JavaScript
var str = "Happy New Years";
var p = str.lastIndexOf(" ");
console.log(p);   // return 9
var p = str.lastIndexOf("/ /gi");
console.log(p);   // return -1
var p = str.lastIndexOf("/\s/gi");
console.log(p);   // return -1
Posted
Updated 2-Jan-23 3:29am

Whitespace in a regex is "\s".
If you are going to use regular expressions, get a copy of Expresso[^] - it's free, and it examines, tests, and generates Regular expressions.
 
Share this answer
 
Comments
Chopin2001 1-Jan-23 15:42pm    
Thanks a lot.
I don't know why it's doesn't work.
lastIndexOf does not support a regex pattern. See here: String.prototype.lastIndexOf() - JavaScript | MDN[^]
 
Share this answer
 
Comments
Chopin2001 2-Jan-23 11:46am    
Wow. I didn't know that. Thanks a lot.
0x01AA 2-Jan-23 11:53am    
You are welcome.
You can use a 'workaround', have a look here: RegExp: lastIndex - JavaScript | MDN[^]

Little bit tricky with a loop, but working ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900