简体   繁体   English

从文本框中切片字符串

[英]Slicing a string from a textbox

I am trying to take a string entered by user from a textbox. 我正在尝试从文本框中获取用户输入的字符串。 Check the length of that string and if the string is over a given number perform the slice operation on it. 检查该字符串的长度,如果该字符串超过给定的数字,请对其执行切片操作。

Here's what I came up with but my code does nothing. 这是我想出的,但是我的代码什么也没做。 Checked console, no errors given. 已检查控制台,未给出错误。

html: HTML:

        <form id="slice">
            Enter a pharse:<input type="text" id="text_box_2"><br>

            <input type="button" value="slice" onclick="Slice()">

            Result: <input type="text" id="slice_result"><br>
        </form>

Javascript function: JavaScript函数:

function Slice(){
    var UserString = document.getElementById("text_box_2").value;
    var UserStringValue = UserString.length;
    var Result = Userstring.slice(1,6);

    if (UserStringValue > 6){
        document.getElementById("Slice_result").value = Result;
    }
    else{
        alert("Please enter a longer phrase.")
    }
}

what or where did I go wrong? 我出了什么问题或哪里出了问题?

from cursory reading of your code. 粗读代码。 it seems caused by this line 似乎是由这条线引起的

var Result = Userstring.slice(1,6);

and also this one 还有这个

document.getElementById("Slice_result").value = Result

it should be 它应该是

var Result = UserString.slice(1,6);

and

document.getElementById("slice_result").value = Result

Be mindful of case-sensitivity. 注意区分大小写。

This: 这个:

var Result = Userstring.slice(1,6);

Should be using UserString (capital "S") as defined earlier in your code. 应该使用前面在代码中定义的UserString (大写的“ S”)。

Next, the input ID should be all lowercase, slice_result , to match to HTML, but your code uses different casing: 接下来,输入ID应该全部为小写字母slice_result ,以匹配HTML,但是您的代码使用不同的大小写:

document.getElementById("Slice_result")

Here's a working JSBin with these fixes. 这是具有这些修复功能的JSBin

EDIT: As JaromandaX mentioned in the comments, if you want to take the first 6 characters you should use slice(0, 6) . 编辑:正如JaromandaX在评论中提到的那样,如果要采用前6个字符,则应使用slice(0, 6) 0,6 slice(0, 6)

Usually use of the following 通常使用以下

var Value = $('#input_id').val();

will pull the requested information for you. 会为您提取所需的信息。

You can also set up arguments for your slice function and pass in the value when you run onclick(); 您还可以为slice函数设置参数,并在运行onclick()时传递该值;

I'd also note that slice() is a current js function, though your implentation with the capital 'S' is some what different, it may be better practice to change that name a bit. 我还要指出,slice()是当前的js函数,尽管您对大写字母'S'的使用有所不同,但最好稍微更改一下名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM