Home > Mobile >  How do I get dynamic index position for a specific character for a input text?
How do I get dynamic index position for a specific character for a input text?

Time:11-26

let's assume an input string has given, for a particular character like '$' you want to add dynamically in the text field , so I want to find the index of a current character like '$' then it's not working properly like initially if I give '$'in any position, its reflection the position, example if I give 'random text$' it returns index 11 but if you type '$'in between text like 'random $text$' then it should return 7, but it returns 12,so by achieving 7 I need to give extra space like 'random $ text$', so dynamically how to get the index position of a current character($), whether It's added in first, middle, last of the text

  let string = "random $text$";
  let newArray = string.split("");
  let store = string.length % 2 !== 0
    ? newArray.findLastIndex((x) => x === "$")
    : newArray.findIndex((x) => x === "$");

  console.log(store);

CodePudding user response:

As you just want to add a space after first occurance of $ in the input string. You can simply achieve that by using String.replace() method instead of looking for index as If pattern in replace function is a string, only the first occurrence will be replaced. The original string is left unchanged.

Live Demo :

function checkIndex(e) {
  const val = e.target.value;
  console.log(val.replace('$', '$ '));
}
<input type="text" id="val" onBlur="checkIndex(event)"/>

Update : Here is the workaround solution but not a good practice to do. For demo, I am using an input and after getting the index, I am replacing the $ with some other character so that I can get the index of current/newly added $.

Demo :

function checkIndex(e) {
  const val = e.target.value;
  if (/$/.test(val)) {
    console.log(val.indexOf('$'))
    document.getElementById('val').value = val.replaceAll('$', '-')
  }
}
<input type="text" id="val" onBlur="checkIndex(event)"/>

CodePudding user response:

I don't really understand why you check for first index/last based on if the total length is even/uneven. However if you want to get all indices you can use a reducer.

const string = "random $text$";
const charToFind = "$";
// Get all indexes of char charToFind in string
let indexes = [...string].reduce((previous, current, i) => {
  // Checks if current value is equal to charToFind otherwise return previous
  return current === charToFind ? [...previous, i] : previous;
}, []);

EDIT: Per OPs new requirements in the comments this is what I could come up with. However its a bit overcomplicated, and will not always work.

// This only take to account of one change, it will not work with paste etc.
const findChar = (newState: string, oldState: string, lastKnownIndices: number[], charToFind: string) => {
  // Find first diff between old and new state
  const firstDiffIndex = newState
    .split("")
    .findIndex((char, index) => char !== oldState[index]);

  // Check if we have added or removed a char 
  const isCharAdded = newState.length > oldState.length;
  // Update last known indices, 
  let newIndices = lastKnownIndices.map((index) => {
    if (index >= firstDiffIndex) {
      return isCharAdded ? index   1 : index - 1;
    }
    return index;
  }).filter((index) => {
    // Remove indices that are no longer valid
    return newState[index] === charToFind;
  });

  // If we added a char, check if it is the char we are looking for
  if (isCharAdded && newState[firstDiffIndex] === charToFind) {
    newIndices = [firstDiffIndex, ...newIndices]
  }

  return {
    newIndices,
    newState,
    lastIndex: newIndices.length > 0 ? newIndices[0] : -1
  }
}

const noCharsToFind = findChar("random text", "random tex", [], "$")
console.log(noCharsToFind)

const addedOneCharToFind = findChar("random $text", noCharsToFind.newState, noCharsToFind.newIndices, "$")
console.log(addedOneCharToFind)

const addedOneMoreCharToFind = findChar("random $text$", addedOneCharToFind.newState, addedOneCharToFind.newIndices, "$")
console.log(addedOneMoreCharToFind)

const removedOneCharToFind = findChar("random text$", addedOneMoreCharToFind.newState, addedOneMoreCharToFind.newIndices, "$")
console.log(removedOneCharToFind)

Here is a link to playground if you want to test more cases

  • Related