SoFunction
Updated on 2025-03-06

Eval function and trim in js remove left and right spaces of strings


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/">
<html>
<head>
<title> New Document </title>
</head>
<body>
There is no trim function in js that handles spaces before and after string filtering, <br>
This very commonly used function is added to jquery, and its source code is as follows
function trim(t){<br>
return (t||"").replace(/^\s+|\s+$/g, "");<br>
}<br>
Sometimes we don't use jquery, there is no need to add the entire jquery library for a function, <br>
At this time, we can copy the source code and write a trim function. <br>
</body>
</html>
<script>
var f='hello';
//alert(f);
/*
By the way, let’s talk about the eval() function, which can use the contents in brackets as js scripts.
You can also calculate mathematical operations or string calculations.
In short, it is not a simple string concatenation function.
You can treat it as a js script in js.
This is very similar to jsp. jsp is Java code embedded in html.
The content in the eval() brackets is the js code embedded in js.
*/
//eval("alert('"+f+"')");//Computing js scripts has the same effect as alert(f).
eval(" var gg='haha'");
alert(eval("gg"));//Eval is the embedded js code, which is equivalent to var gg='haha',alert(gg);
//alert(eval('3+4'));//calculate mathematical operations, result 7
//alert(eval('3'+'4'));//calculate the string, result 34
alert("start"+trim(' abc def ')+"end");
//The trim function in jquery filters out the first space.
function trim(t){
return (t||"").replace(/^\s+|\s+$/g, "");
}
</script>