如何将输入的单词组合起来?

How can i combine words from input?

本文关键字:组合 起来 单词 输入      更新时间:2023-09-26

例如,如果我有这样的表单:

  <form >
        <input type="text" name="name" id="my_input">
        <input id="search_tags" type="submit" value="Search">
  </form>

我写了"example",#my_input'的"item"值为"example item"。我如何从书面文字中构建这样的东西:'/example-item/' ?

var combinedWord = "/" + $("#my_input").val().replace(/ /g, "-") + "/";

使用正则表达式…也许是价值之类的东西。替换(/[^ ' w ' d] +/gi,"-");它将取代任何不是数字或字母的东西。这看起来像是你可能想要做的。

var value = "example item 2";
value.replace(/[^'w'd]+/gi, '-');
console.log(value) // will be example-item-2
value = '/' + value + '/';
console.log(value) // will be '/example-item-2/'

如果您想为每个输入都做此操作,则

var combinedWord;
$("input[type=text]").each(function()
{
combinedWord+=$(this).val();    //if space between different input is to be maintained then add .replace(' ', '-') here
});
return "/" + combinedWord + "/"; //if all spaces need to be replaced add .replace(' ', '-') here.

用连字符代替所有空格:

var my_input_val = $('#my_input').val().replace(/'s/g, '-');

然后将正斜杠连接到任意一端:

var concat_my_input = '/' + my_input_val + '/';

.replace()是一个非常灵活的函数,既可以匹配正则表达式,也可以匹配字符串。更多信息请参见w3schools定义