简体   繁体   English

如何在JavaScript中剪切字符串的特定部分

[英]How to cut specific part of string in javascript

I tried to get value of image src with click event by using this: 我试图通过使用以下事件来获取带有单击事件的图像src的值:

<img onclick='swap(this); return false;' style='width:auto;max-width:65px;max-height:55px' src="/member/sthumb/$image_path_array[$i]">

So when i click it, i get this value /member/sthumb/$image_path_array[$i] 因此,当我单击它时,我得到的值是/member/sthumb/$image_path_array[$i]

Here is my javascript code: 这是我的JavaScript代码:

<script type="text/javascript">
   function swap(image) {
      ...some code to cut the sthumb/ part from the string
      document.getElementById("main").src = image.src;
   }
</script> 

In this javascript code, i would like to cut this specific part sthumb/ out so the image.src will now be: /member/$image_path_array[$i] 在这段JavaScript代码,我想剪这特定部分sthumb/出这样image.src现将: /member/$image_path_array[$i]

Use String.replace() 使用String.replace()

function swap(image) {
    //...some code to cut the sthumb/ part from the string
    document.getElementById("main").src = image.src.replace('/sthumb', '');
}
You can use simple replace method of String or it can be done using substring also
Solution1(Simple and Best):
function swap(image) {
    document.getElementById("main").src = image.src.replace('/sthumb', '');
}

Solution2:
function swap(image) {
var str=image.src;
var StringToCut='/sthumb';
document.getElementById("main").src = str.substring(0,str.indexOf(StringToCut))+str.substring(str.indexOf(StringToCut)+StringToCut.length);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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