Javascript line splitting

I have a variable named s in javascript.It contains a value like '40 & lngDesignID = 1 '. I want to break it and want to get 40 and lngDesignID = 1. How can I do this in javascript? Can anyone help?

+1
source share
3 answers

Use s.split ("&") to return an array of elements.

var string = "40&lngDesignID=1";
var splitVals = string.split("&");

alert(splitVals[0]); // Alerts '40'
alert(splitVals[1]); // Alerts 'lngDesignID=1'
+7
source
var yourString = '40&lngDesignID=1';

var arr = yourString.split('&');
alert(arr);

Then arr [0] will contain '40', and arr [1] will contain the value 'lngDesignID = 1'.

In addition, javascript split accepts regular expressions, so you can also split the string if necessary.

var yourString = '40&lngDesignID=1';

var arr = yourString.split(/[&=]/);
alert(arr);

This version splits the input into 3 parts; 40, lngDesignID and 1.

+2

Do not use ampersand for any string operation. If you ever have to compare variables that get their values ​​from HTML and contain ampersands, you will find ampersands transformed into entities, which ruined your comparison or evaluation. Use another character that you would never use, such as a tilde or a carriage.

0
source

Source: https://habr.com/ru/post/1016980/


All Articles