2015-10-29 34 views
0

我需要定義要從第(4)次刪除的文本區域並保留擴展名。 後34_567_890_123.jpg刪除指定位置的範圍起始事件

12_345_678_900.jpg12_345_678_900_xxxxxxxxxxxxxxx.jpg之前,

34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg

這可能嗎?

+2

左右,基本...是的! –

+0

是第一部分總是一樣的長度?如果是這樣,你可以使用子字符串 – depperm

+0

看看http://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string –

回答

0

一個解決方案是找到nth occurence,然後使用子字符串。

var one='12_345_678_900_xxxxxxxxxxxxxxx.jpg'; // 12_345_678_900.jpg 
 

 

 
function nth_occurrence (string, char, nth) { 
 
    var first_index = string.indexOf(char); 
 
    var length_up_to_first_index = first_index + 1; 
 

 
    if (nth == 1) { 
 
     return first_index; 
 
    } else { 
 
     var string_after_first_occurrence = string.slice(length_up_to_first_index); 
 
     var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1); 
 

 
     if (next_occurrence === -1) { 
 
      return -1; 
 
     } else { 
 
      return length_up_to_first_index + next_occurrence; 
 
     } 
 
    } 
 
} 
 

 
console.log(one.substring(0,nth_occurrence(one,'_',4))+one.substring(one.indexOf('.')));

0

當然,通過拆分 「_」,然後加入回數據,你想:

var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg"; 
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1) 
console.log(str) 
0

正則表達式是非常適合這種情景:

const data1 = '12_345_678_900_xxxxxxxxxxxxxxx.jpg' 
const data2 = '34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg' 
const re = /^([^_]+_[^_]+_[^_]+_[^_]+).*(.jpg)$/; 

var test1 = data1.replace(re, '$1$2'); 
var test2 = data2.replace(re, '$1$2'); 

試一試:https://jsfiddle.net/648xt3qq/

有可能是會得到

0

完成工作的幾個不同的正則表達式的方法或許這對你的作品:

function clean() { 
 
    var el = document.getElementById('area'); 
 
    el.value = el.value.replace(/^(.*?_.*?_.*?_.*?)(_.*?)(\..*?.*)$/gmi, '$1$3'); 
 
}
<form action=""> 
 
    <textarea cols="50" rows="4" id="area">12_345_678_900_xxxxxxxxxxxxxxx.jpg 
 
34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg</textarea><br /> 
 
    <input type="submit" onclick="clean(); return false;" /> 
 
</form>