0

I have a string like this "aadsa&ss))as(d?", i want to get index of all the special characters from it. I have tried following and getting the values, but i am sure there will be some better way of doing this.

  var str = "aadsa&ss))as(d?";
  var indexes = [];

  for (var i = 0; i < str.length; i++) {

   if (str[i] === "&" || str[i] === "*" || str[i] === "(" || str[i] === ")" || str[i] === ">" || str[i] === "<" || str[i] === "?") {
         indexes.push(i);
   }

}
Elias
  • 3,592
  • 2
  • 19
  • 42
learner1
  • 116
  • 1
  • 15
  • What are you intending to do after you get all the indexes? – Taplar Oct 01 '18 at 14:38
  • [duplicate](https://stackoverflow.com/questions/32311081/check-for-special-characters-in-string) – Alexandre Elshobokshy Oct 01 '18 at 14:40
  • quite a long process, after getting index of special characters i want to replace those characters based on two condition, if they are between alphabets then replace by - , and if they are between numbers then simply remove it. – learner1 Oct 01 '18 at 14:40

2 Answers2

1

It can be achieved by RegExp.

First, I replced all spaces (if any) with 'i' as it is not a special character, and then I have used /\W/ to search all special characters using String.search().

Then, in the while loop while i searched for special characters I used String.replace() to replace those special characters with 'i' again, so that they couldn't be found again.

var str = "aadsa&ss))as(d?";
var cpy = str;
var indexes = [];
cpy = cpy.replace(/\s+/g, 'i');
while(/\W/.test(cpy)) {
  indexes.push( cpy.search(/\W/) );
  cpy = cpy.replace(/\W/, 'i');
}

console.log(indexes);
vrintle
  • 5,501
  • 2
  • 16
  • 46
1

As shown before you should probably do it via regex but here still the answer to your question:

let str = "aadsa&ss))as(d?";
let specialChars = ["(", ")", "&", "?"];
let indexes = [];

for(let i = 0; i < str.length; i++) {
  if(specialChars.indexOf(str[i]) != -1) indexes.push(i);
}

console.log(indexes);

You can of course put all the characters you like into the array :)

Elias
  • 3,592
  • 2
  • 19
  • 42