i am trying to heck if a string (first argument, str) ends with the given target string (second argument, target).  function confirmEnding(str, target) {   return  /target$/.test(str) }
Test stringconfirmEnding("Bastian","n") show false. What i am doing wrong? Can i use regular expression as argument of function?
;
            Asked
            
        
        
            Active
            
        
            Viewed 37 times
        
    0
            
            
         
    
    
        nadia12221
        
- 1
- 1
- 
                    Does this answer your question? [endsWith in JavaScript](https://stackoverflow.com/questions/280634/endswith-in-javascript) Also relevant: [How do you use a variable in a regular expression?](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression) – DBS Jul 01 '22 at 14:49
1 Answers
2
            
            
        If it's always a string, then you can just use String#endsWith
function checkEnd(str, target) {
  return str.endsWith(target);
}
console.log(checkEnd("Bastion", "n"));If you want to cast target into a regex, but note that this won't escape out any of the special characters in target. i.e. checkEnd('special)',')') will fail due to the regex being invalid:
function checkEnd(str, target) {
  return new RegExp(`${target}$`).test(str);
}
console.log(checkEnd("Bastion", "n")); 
    
    
        Zachary Haber
        
- 10,376
- 1
- 17
- 31