Shivaji Watekar
Shivaji Watekar

Reputation: 71

How to find special characters in a string and store in an array in javascript

Example of a string

"/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>"

characters occurs like A, B, C and .... are variables and count is not fixed

How to identifies how many variables are there and stored in an array

Upvotes: 0

Views: 1000

Answers (2)

Dipak
Dipak

Reputation: 2308

Please review below code that will help to resolve your issue. It may find any non word characters and create a non-word array.

let str = "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>";

let arrStr = str.split("");
var strRegExp = /\W/g;
let arrNonWord = [];

arrStr.forEach(function(str){
  var result = str.match(strRegExp);
  if(result)
  	arrNonWord.push(result[0]);
});

console.log(arrNonWord);

Upvotes: 0

itdoesntwork
itdoesntwork

Reputation: 1891

Use regex to find all your matches. Using a while loop you can iterate through multiple matches and push them in an array. Try this.

var String = "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>";
var myRegexp = /\<.\>/gm;
var matches = [];
var match = myRegexp.exec(String);

while (match != null) {  
  matches.push(match[0])
  match = myRegexp.exec(String);
}

console.log(matches)

Upvotes: 2

Related Questions