Return the split value if the user had entered the path else return blank

十年热恋 提交于 2019-12-25 09:04:06

问题


I need to display the name and split path of the path entered by a user dynamically. For that, I had split the path entered by the user and grab only certain part of it. For e.g. if the user enters path as:

/content/mypath/myfolder/about/images/abc.jpg Then I am displaying images/abc.jpg.

However, let's say the user only enters the name and doesn't enter the path, at least the name should be applied & displayed in that case.

But it displays 0 everytime I enter a path. How do I fix this?

$(document).ready(function(){
  $('#getData').click(function(){
    var name = $('#name').val();
    var imgPath = $('#imgPath').val();
    var newPath = imgPath.match(/images\/.*$/i);
    $('.container').append(
      $('<p>').text(name),
      $('<p>').text(function(imgPath){
        return newPath ? imgPath : $('#imgPath').val();
      })
    );
    //console.log(slicedPath);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Name: <input type="text" id="name">
Image path: <input type="text" id="imgPath">
<div class="container">

</div>
<button id="getData">Click</button>

回答1:


This should solve your problem.

I've only changed your return statement return newPath != null ? newPath : imgPath;

$(document).ready(function(){
  $('#getData').click(function(){
    var name = $('#name').val();
    var imgPath = $('#imgPath').val();
    var newPath = imgPath.match(/images\/.*$/i);
    $('.container').append(
      $('<p>').text(name),
      $('<p>').text(function(imgPath){
        return newPath != null ? newPath : $('#imgPath').val();
      })
    );
    //console.log(slicedPath);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Name: <input type="text" id="name">
Image path: <input type="text" id="imgPath">
<div class="container">

</div>
<button id="getData">Click</button>


/content/mypath/myfolder/about/images/abc.jpg


来源:https://stackoverflow.com/questions/43535696/return-the-split-value-if-the-user-had-entered-the-path-else-return-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!