0

How can I remove matching string with comma before or after

Ex :

<input value="1,2,3,4,5,6,7,8,9,10">

jQuery :

var input = $("input");
var val = input.val();
var random = Math.ceil(Math.random() * 10);
var new_val = val.replace(random,"");

input.val(new_val);

Values not look like 1-10 (this is a example)

Problem with how can I remove comman before or after too ?

Think about if matching string has first position and last position. So it's problem

PS : I have to find by string, not index or something else

Playground : http://jsbin.com/ulikof/1/edit

Any ?

2 Answers 2

2

If add you add the trailing comma when selecting the random number, it will remove the single comma and display correctly:

var input = $("input");
var val = input.val();
var random = Math.ceil(Math.random() * 10);

if(val.indexOf(random) != 0) {
  random = ',' + random;
}
else {
  random = random + ','; 
}

var new_val = val.replace(random,"");

input.val(new_val);
Sign up to request clarification or add additional context in comments.

2 Comments

what about last string like 10 cannot replace by 10, its not found
+ else if (val === random) {random = random} , if just only one string left
1

Here's a generic way using pure JS in which you could add any amount of numbers without updating the code.

http://jsfiddle.net/zuMNf/1/

var input = document.getElementsByTagName('input')[0], // [0] or loop through inputs
    val = input.value,
    arr = val.split(','),
    len = arr.length,
    random = Math.ceil(Math.random() * len);

for(var i = 0; i < len; i++) {
    if(parseInt(arr[i]) == random) {
        var j = i;
    }
};

arr.splice(j, 1);

input.value = arr.join(',');

1 Comment

No , I have to find with string , not index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.